32

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!

rightfold
  • 30,950
  • 10
  • 83
  • 106
dedalo
  • 2,441
  • 12
  • 30
  • 34

3 Answers3

67
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]));
Adeel Ansari
  • 38,068
  • 12
  • 89
  • 127
bruno conde
  • 46,109
  • 14
  • 94
  • 114
8
for (int j=0; j<test.length; j++) {
   System.out.format("%02X ", test[j]);
}
System.out.println();
Carl Smotricz
  • 62,722
  • 17
  • 119
  • 161
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)

Dan Rosenstark
  • 64,546
  • 54
  • 267
  • 405
jeff porter
  • 6,196
  • 13
  • 59
  • 112