James Meade
James Meade

Reputation: 1169

How to convert byte array to hex format in Java

I know that you can use printf and also use StringBuilder.append(String.format("%x", byte)) to convert values to HEX values and display them on the console. But I want to be able to actually format the byte array so that each byte is displayed as HEX instead of decimal.

Here is a section of my code that I have already that does the first two ways that I stated:

if(bytes > 0)
    {
        byteArray = new byte[bytes]; // Set up array to receive these values.

        for(int i=0; i<bytes; i++)
        {
            byteString = hexSubString(hexString, offSet, CHARSPERBYTE, false); // Isolate digits for a single byte.
            Log.d("HEXSTRING", byteString);

            if(byteString.length() > 0)
            {
                byteArray[i] = (byte)Integer.parseInt(byteString, 16); // Parse value into binary data array.
            }
            else
            {
                System.out.println("String is empty!");
            }

            offSet += CHARSPERBYTE; // Set up for next word hex.    
        }

        StringBuilder sb = new StringBuilder();
        for(byte b : byteArray)
        {
            sb.append(String.format("%x", b));
        }

        byte subSystem = byteArray[0];
        byte highLevel = byteArray[1];
        byte lowLevel = byteArray[2];

        System.out.println("Byte array size: " + byteArray.length);
        System.out.printf("Byte 1: " + "%x", subSystem);
        System.out.printf("Byte 2: " + "%x", highLevel);
        System.out.println("Byte 3: " + lowLevel);
        System.out.println("Byte array value: " + Arrays.toString(byteArray));
        System.out.println("Byte array values as HEX: " + sb.toString());
    }
    else
    {
        byteArray = new byte[0]; // No hex data.

        //throw new HexException();
    }

    return byteArray;

The string that was split up into the byte array was:

"1E2021345A2B"

But displays it as decimal on the console as:

"303233529043"

Could anyone please help me on how to get the actual values to be in hex and be displayed in that way naturally. Thank you in advance.

Upvotes: 13

Views: 46744

Answers (4)

VGR
VGR

Reputation: 44338

String.format actually makes use of the java.util.Formatter class. Instead of using the String.format convenience method, use a Formatter directly:

Formatter formatter = new Formatter();
for (byte b : bytes) {
    formatter.format("%02x", b);
}
String hex = formatter.toString();

As of Java 17, HexFormat can do this in one line:

String hex = HexFormat.of().formatHex(bytes);

Upvotes: 28

Dharmesh Gohil
Dharmesh Gohil

Reputation: 334

Try this

byte[] raw = some_bytes;
javax.xml.bind.DatatypeConverter.printHexBinary(raw)

Upvotes: 2

Paul Vargas
Paul Vargas

Reputation: 42020

You can use the String javax.xml.bind.DatatypeConverter.printHexBinary(byte[]). e.g.:

public static void main(String[] args) {
    byte[] array = new byte[] { 127, 15, 0 };
    String hex = DatatypeConverter.printHexBinary(array);
    System.out.println(hex); // prints "7F0F00"
}

Upvotes: 31

Tamas
Tamas

Reputation: 3442

The way I do it:

  private static final char[] HEX_CHARS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
      'B', 'C', 'D', 'E', 'F' };

  public static String toHexString(byte[] bytes) {
    char[] hexChars = new char[bytes.length * 2];
    int v;
    for (int j = 0; j < bytes.length; j++) {
      v = bytes[j] & 0xFF;
      hexChars[j * 2] = HEX_CHARS[v >>> 4];
      hexChars[j * 2 + 1] = HEX_CHARS[v & 0x0F];
    }
    return new String(hexChars);
  }

Upvotes: 6

Related Questions