Java: Simply convert a decimal byte to a hexadecimal byte

byte, decimal, hex, java

Solution

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

Problem

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`.

Original source