Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Simply convert a decimal byte to a hexadecimal byte

I want to get this:

byte dec = 10;

to this:

byte hex = 0x0A;

But I can't find the solution anywhere. I see always String s = Integer.parseInt(... But I don't want a String as result. I want a byte.

like image 570
KeksArmee Avatar asked Sep 06 '25 19:09

KeksArmee


1 Answers

A byte is just a sequence of bits in memory -- it doesn't matter how it's represented visually, and two different representations can mean the same thing. If all you want is a hex literal, you can try this:

byte dec = 10;
byte hex = 0xA;  // hex literal

System.out.println(dec == hex);
true

Note that dec and hex are exactly identical here; 10 and 0xA represent the same number, just in different bases.

If you want to display a byte in hex, you can use Integer.toHexString():

byte dec = 10;
System.out.println(Integer.toHexString(dec));
a
like image 189
arshajii Avatar answered Sep 09 '25 19:09

arshajii