I am trying to write a binary string into a file and afterwords read it and present it in a hex representation. This is my code:
import java.io.*;
import java.math.BigInteger;
public class TestByte {
public static void main(String[] argv) throws IOException {
String bin = "101101010110001000010011000000000100010000000001000000000000000100000000000000000000000000000000000010110000000000111111000101010001100000000000000000000000000000001000000000000000000000111110011111000000000010110011";
//write binary file
DataOutputStream out = null;
File fileout = new File("binout.bin");
out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(fileout)));
int indx = 0;
for (int i = 0; i < bin.length()/8; i++){
System.out.println(bin.substring(indx, indx+8));
byte[] bytesout = new BigInteger(bin.substring(indx, indx+8),2).toByteArray();
out.write(bytesout);
indx += 8;
}
out.close();
//read binary file
File filein = new File("binout.bin");
byte[] bytesin = new byte[(int) filein.length()];
FileInputStream inputStream = new FileInputStream(filein);
inputStream.read(bytesin);
inputStream.close();
StringBuilder sb = new StringBuilder();
for (byte b : bytesin) {
sb.append(String.format("%02X ", b));
}
System.out.println(sb.toString());
}}
The program works, however, there are some inconsistencies with the data. This is the output:
10110101 01100010 00010011 00000000 01000100 00000001 00000000 00000001 00000000 00000000 00000000 00000000 00001011 00000000 00111111 00010101 00011000 00000000 00000000 00000000 00001000 00000000 00000000 00111110 01111100 00000000 10110011
00 B5 62 13 00 44 01 00 01 00 00 00 00 0B 00 3F 15 18 00 00 00 08 00 00 3E 7C 00 00 B3
As you can see, I have broken the binary string into pieces of 8 bits so it would be easier to follow the numbers. The inconsistency is the Hex representation. It seems there is an extra "00" at the beginning of the hex string, which should not be there. Also there is an extra "00" in the end of the string, the should be only one "00" before the "B3".
Can anyone shed some light on this problem and/or make the solution more elegant? Any help would be appreciated. Thank you.