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.
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
Unfortunately, you can not get "A" as a byte. Bytes are an extension of numbers, so you can only hold numeric values here. What you may wish to do is to return a char that represents the hex, or a String.
Something like this might be of use:
package sandbox;
public class Sandbox
{
public static void main(String[] args)
{
byte value = 1;
char charValue = getHex(value);
System.out.println(charValue);
}
private static char getHex(byte b)
{
Byte bObj = new Byte(b);
if (b < 10) { return bObj.toString().charAt(0); }
else
{
char hexChar = (char)(bObj.toString().charAt(1) + 'A' - '0');
return hexChar;
}
}
}
I hope i have been helpful.
byte hex = 0x00; for(byte i=1; i<dec+1; i++) {++hex}byte hex = dec;and it will give exactly the same result as your loop.