Skip to content

Instantly share code, notes, and snippets.

@kylepls
Created July 18, 2017 05:38
Show Gist options
  • Save kylepls/08bb6c9b75d55ebd85f95d3607c33a4a to your computer and use it in GitHub Desktop.
Save kylepls/08bb6c9b75d55ebd85f95d3607c33a4a to your computer and use it in GitHub Desktop.
Would rather use P's and Q's rather than binary
package in.kyle.api;
/**
* P = 0
* Q = 1
*/
public class PsAndQs {
private static final byte[] BIT_MASKS =
new byte[]{0b1000000, 0b1000000, 0b100000, 0b10000, 0b1000, 0b100, 0b10, 0b1};
public static String encode(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
for (byte mask : BIT_MASKS) {
if ((b & mask) == mask) {
sb.append("q");
} else {
sb.append("p");
}
}
}
return sb.toString();
}
public static byte[] decode(String encodedString) {
char[] chars = encodedString.toCharArray();
if (chars.length % 8 != 0) {
throw new IllegalArgumentException("Invalid input string, not % 8, " + chars.length);
}
byte[] bytes = new byte[chars.length / 8];
for (int i = 0; i < chars.length; i += 8) {
byte value = 0;
for (int j = 0; j < 8; j++) {
if (chars[i + j] == 'q') {
value |= BIT_MASKS[j];
}
}
bytes[i / 8] = value;
}
return bytes;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment