Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

byte

system

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!

like image 736
dedalo Avatar asked Nov 17 '09 10:11

dedalo


People also ask

How do you convert bytes to hexadecimal?

To convert byte array to a hex value, we loop through each byte in the array and use String 's format() . We use %02X to print two places ( 02 ) of Hexadecimal ( X ) value and store it in the string st .

How to print out hexadecimal in Java?

Displaying Hexadecimal Number in Javaout. println(String. format("%x", y)); This is a complete example showing how an integer is displayed in hexadecimal.

How do I print a byte array?

You can simply iterate the byte array and print the byte using System. out. println() method.

How do I printf a byte?

Assumption:You want to print the value of a variable of 1 byte width, i.e., char . In case you have a char variable say, char x = 0; and want to print the value, use %hhx format specifier with printf() . printf("%x", x);


3 Answers

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]));
like image 59
bruno conde Avatar answered Oct 06 '22 04:10

bruno conde


for (int j=0; j<test.length; j++) {
   System.out.format("%02X ", test[j]);
}
System.out.println();
like image 31
Carl Smotricz Avatar answered Oct 06 '22 05:10

Carl Smotricz


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)

like image 29
jeff porter Avatar answered Oct 06 '22 05:10

jeff porter