Jun
02
|
You can use BigInteger class to convert a byte array into its hex (or binary) representation. However for large byte arrays this method is slow.
For large byte arrays and where performance is important you can use the following utility method to convert each byte to its binary representation.
public static String toBinaryString(byte n) { StringBuilder sb = new StringBuilder("00000000"); for (int bit = 0; bit < 8; bit++) { if (((n >> bit) & 1) > 0) { sb.setCharAt(7 - bit, '1'); } } return sb.toString(); }
Array ( ) 9 Responses to “Converting large byte array to binary string”
Leave a Reply
You must be logged in to post a comment.
June 11th, 2010 at 2:25 am
That’s a great solution thanks. Could you post how to convert it back? For example if I have a string array with binary data. How do it convert that to a byte array.
Thanks.
June 11th, 2010 at 9:45 am
Glad you enjoyed the solution. For going the other way see “How to parse a binary String”
August 20th, 2010 at 5:14 am
I need to convert “binary to byte array”.
I wanna convert photo file to byte array -> binary and den i wanna go in reverse i.e
binary -> byte array -> photo..
can anyone help me pls…
August 20th, 2010 at 10:08 am
First read the file into a byte array, then convert it to a binary string.
August 24th, 2010 at 9:59 pm
article, worthy to command. It’s everything here exactly what I need to know.
March 4th, 2011 at 5:07 am
Thanks a lot, I used it to load a whole large files (100xkB) in binary format – works great!
July 3rd, 2011 at 4:45 am
Thank you for the information, this is really helpful for me. Hope there will be more in the coming days.
Ashok Sunar
Student in IOE
Pokhara, Nepal
July 29th, 2011 at 4:26 am
superb post man…!!!
thxx a lot…!!!
February 26th, 2012 at 12:03 am
how to perform xor operation on two or more files using java