Search code examples
javaarraysbit-manipulationhexdump

how to convert bit array into hex contanning 8bits in java


I have binary array i converted into hex using

    StringBuilder sb = new StringBuilder();
    for (byte b : bytes) 
    {
        sb.append(String.format("%02X ", b));
    }
    System.out.println(sb.toString());

But it gives me hex code for its respective bit.

I want hex containing 8bits. Please help me.


Solution

  • You want something like this-

    BigInteger bInt = new BigInteger(1, bytes);
    String hexString = String.format("%0" + (bytes.length << 1) + "X", bInt);
    

    For lower case hex digits, you can use-

    String hexString = String.format("%0" + (bytes.length << 1) + "x", bInt);