How to print bytes in hexadecimal using System.out.println?

109,122

Solution 1

System.out.println(Integer.toHexString(test[0]));

OR (pretty print)

System.out.printf("0x%02X", test[0]);

OR (pretty print)

System.out.println(String.format("0x%02X", test[0]));

Solution 2

for (int j=0; j<test.length; j++) {
   System.out.format("%02X ", test[j]);
}
System.out.println();

Solution 3

byte test[] = new byte[3];
test[0] = 0x0A;
test[1] = 0xFF;
test[2] = 0x01;

for (byte theByte : test)
{
  System.out.println(Integer.toHexString(theByte));
}

NOTE: test[1] = 0xFF; this wont compile, you cant put 255 (FF) into a byte, java will want to use an int.

you might be able to do...

test[1] = (byte) 0xFF;

I'd test if I was near my IDE (if I was near my IDE I wouln't be on Stackoverflow)

Share:
109,122
dedalo
Author by

dedalo

Updated on July 26, 2020

Comments

  • dedalo
    dedalo almost 4 years

    I've declared a byte array (I'm using Java):

    byte test[] = new byte[3];
    test[0] = 0x0A;
    test[1] = 0xFF;
    test[2] = 0x01;
    

    How could I print the different values stored in the array?

    If I use System.out.println(test[0]) it will print '10'. I'd like it to print 0x0A

    Thanks to everyone!

  • dwc
    dwc over 14 years
    Of all of these, the System.out.printf is probably the best idea.
  • Anirban Nag 'tintinmj'
    Anirban Nag 'tintinmj' over 10 years
    But the Integer.toHexString will print 10 not 0x0A.
  • Per Christian Henden
    Per Christian Henden over 10 years
    You can definitely do byte b = 255 & 0xFF; And then when reading it int calculation = (0xFF &b) + 5; to read back 255