Skip to content

Instantly share code, notes, and snippets.

@WOLOHAHA
Last active August 29, 2015 14:04
Show Gist options
  • Select an option

  • Save WOLOHAHA/5a497bffd27058b68247 to your computer and use it in GitHub Desktop.

Select an option

Save WOLOHAHA/5a497bffd27058b68247 to your computer and use it in GitHub Desktop.
A monochrome screen is stored as a single array of bytes, allowing eight consecutive pixels to be stored in one byte. The screen has width w, where w is 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 function drawHorizontalLi…
package POJ;
import java.util.ArrayList;
public class Main{
/**
*
* 5.8 A monochrome screen is stored as a single array of bytes, allowing eight consecutive pixels to be stored
* in one byte. The screen has width w, where w is 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
* function drawHorizontalLine(byte[] screen, int width, int x1, int x2, int y) which draws a horizontal line from
* (x 1, y) to (x2, y).
*
*/
// public static void main(String[] args) {
// Main so = new Main();
// }
public 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 last_full_byte = x2 / 8;
if (end_offset != 7)
last_full_byte--;
// set full bytes
for (int i = first_full_byte; i <= last_full_byte; i++)
screen[y * (width / 8) + i] = (byte) 0xFF;
// create masks for start and end of line;
byte startMask = (byte) (0xFF >> start_offset);
byte endMask = (byte) ~(0xFF >> (end_offset + 1));
// set start and end of line
if ((x1 / 8) == (x2 / 8)) {
// x1 and x2 are in the same byte
byte mask = (byte) (startMask & endMask);
screen[y * (width / 8) + x1 / 8] |= mask;
} else {
if (start_offset != 0) {
screen[y * (width / 8) + first_full_byte - 1] |= startMask;
}
if (end_offset != 7) {
screen[y * (width / 8) + last_full_byte + 1] |= endMask;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment