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();

written by objects \\ tags: , , , ,

Array ( ) 9 Responses to “Converting large byte array to binary string”

  1. Jenn Says:

    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.

  2. objects Says:

    Glad you enjoyed the solution. For going the other way see “How to parse a binary String”

  3. steve Says:

    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…

  4. objects Says:

    First read the file into a byte array, then convert it to a binary string.

  5. Quentin Rella Says:

    article, worthy to command. It’s everything here exactly what I need to know.

  6. Tom Says:

    Thanks a lot, I used it to load a whole large files (100xkB) in binary format – works great!

  7. InaComputer Says:

    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

  8. Nayan Says:

    superb post man…!!!
    thxx a lot…!!!

  9. Arun Says:

    how to perform xor operation on two or more files using java

Leave a Reply

You must be logged in to post a comment.