I need to convert ASCII characters to (7-bit) binary. I have seen this, but it gives me the binary value in 8 bits, meanwhile i want it to be in 7 bits. For instance:
C
should be 1000011
CC
should be 10000111000011
%
should be 0100101
So, I changed the code to:
String s = "%";
byte[] bytes = s.getBytes();
StringBuilder binary = new StringBuilder();
for (int j = 0; j < 7; j++) {
int val = bytes[j];
for (int i = 0; i < 8; i++) {
binary.append((val & 128) == 0 ? 0 : 1);
val <<= 1;
}
binary.append("");
}
System.out.println("'" + s + "' to binary: " + binary);
and it complains with:
java.lang.ArrayIndexOutOfBoundsException: 1
in the line:
int val = bytes[j];
To highlight:
I used
for(int j=0;j<7;j++)
int val = bytes[j];
instead of
for (byte b : bytes)
int val = b;