Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Example code from http://stackoverflow.com/questions/9349519/how-to-convert-boolean-array-to-binary-and-vice-versa-in-java
- private static void writeBooleans(OutputStream out, boolean[] ar) throws IOException
- {
- for (int i = 0; i < ar.length; i += 8)
- {
- int b = 0;
- for (int j = Math.min(i + 7, ar.length-1); j >= i; j--)
- {
- b = (b << 1) | (ar[j] ? 1 : 0);
- }
- out.write(b);
- }
- }
- private static void readBooleans(InputStream in, boolean[] ar) throws IOException
- {
- for (int i = 0; i < ar.length; i += 8)
- {
- int b = in.read();
- if (b < 0) throw new EOFException();
- for (int j = i; j < i + 8 && j < ar.length; j++)
- {
- ar[j] = (b & 1) != 0;
- b >>>= 1;
- }
- }
- }
- My code, with variable names changed for clarity and consistency with the above example:
- Grid is a square of GridSize height and width.
- For writing:
- for(int y = 0; y < gridSize; y++)
- {
- for(int i = 0; i < gridSize; i += 8)
- {
- int b = 0;
- for(int j = Math.min(i + 7, gridSize - 1); j >= i; j--)
- b = (b << 1) | (grid.get(i, y) ? 1 : 0); // if grid were a boolean[][], grid.get(i, y) would be grid[i][y]
- output.write(b);
- }
- }
- For reading:
- for(int y = 0; y < gridSize; y++)
- {
- for(int i = 0; i < gridSize; i += 8)
- {
- int b = input.read();
- if(b < 0)
- throw new EOFException();
- for(int j = i; j < i + 8 && j < gridSize; j++)
- {
- grid.set(j, y, (b & 1) != 0); // Or, if grid were a boolean[][], grid[j][y] = (b & 1) != 0;
- b >>>= 1;
- }
- }
- }
- My code, with actual variable names:
- For writing:
- for(int y = 0; y < regionSize; y++)
- {
- for(int x = 0; x < regionSize; x += 8)
- {
- int b = 0;
- for(int i = Math.min(x + 7, regionSize - 1); i >= x; i--)
- b = (b << 1) | (region.get(x, y) ? 1 : 0);
- output.write(b);
- }
- }
- For reading:
- for(int y = 0; y < regionSize; y++)
- {
- for(int x = 0; x < regionSize; x += 8)
- {
- int b = input.read();
- if(b < 0)
- throw new EOFException();
- for(int i = x; i < x + 8 && i < regionSize; i++)
- {
- region.set(i, y, (b & 1) != 0);
- b >>>= 1;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment