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!
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 .
Displaying Hexadecimal Number in Javaout. println(String. format("%x", y)); This is a complete example showing how an integer is displayed in hexadecimal.
You can simply iterate the byte array and print the byte using System. out. println() method.
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);
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]));
for (int j=0; j<test.length; j++) {
System.out.format("%02X ", test[j]);
}
System.out.println();
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With