Q: A monochrome screen is stored as a singal array of bytes, allowing eight consecutive pixels to be stored in one byte. The screen has width w, where w is a divisible by 8 (that is, no byte will be split across rows). The height of the screen , of course, can be derived from the length of the array and the width. Implement a functin drawHorizontalLine(byte[] screen, int width, int x1, int x2, int y) which draws a horizontal line from (x1, y) to (x2, y).
A:
思路1: 逐像素置1即可。
思路2:逐字节置1。 注意一下边界情况的处理。
#include <iostream>
using namespace std;
typedef unsigned char BYTE;
void drawLine(BYTE screen[], int width, int x1, int x2, int y) {
int start_offset = x1%8;
int first_full_byte = x1/8;
if (start_offset != 0) {
first_full_byte++;
}
int end_offset = x2%8;
int end_full_byte = x2/8;
if (end_offset != 7) {
end_full_byte--;
}
for (int i = first_full_byte; i <= end_full_byte; i++) {
screen[(width/8)*y+i] = (BYTE) 0xFF;
}
BYTE start_mask = (BYTE) (0xFF>>start_offset);
BYTE end_mask = (BYTE) ~(0xFF>>(end_offset+1));
if ((x1/8) == (x2/8)) {
BYTE mask =(BYTE) start_mask&end_mask;
screen[(width/8)*y+x1/8] |= mask;
} else {
if (start_offset != 0) {
int ind = (width/8)*y + first_full_byte - 1;
screen[ind] |= start_mask;
}
if (end_offset != 7) {
int ind = (width/8)*y + end_full_byte + 1;
screen[ind] |= end_mask;
}
}
}