4

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.

2
  • I think I got the solution: byte hex = 0x00; for(byte i=1; i<dec+1; i++) {++hex} Commented Feb 12, 2014 at 15:47
  • 4
    There's no such thing as a "decimal byte" or a "hex byte". It's just a number. You can use byte hex = dec; and it will give exactly the same result as your loop. Commented Feb 12, 2014 at 15:49

2 Answers 2

9

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
Sign up to request clarification or add additional context in comments.

2 Comments

@KeksArmee I'm not sure what you mean. Do you want to display a byte in a hexadecimal format?
you said that there is no hexa/dec byte in java. at first i wanted to store it in hex, since that is not possible i have to display it in hex as a string. so, yes.
0

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.

4 Comments

He likely means "A" in the hexadecimal system, which is 10 in decimal.
I agree. However, since these are the same in a byte primitive, i am providing for any other possible interpretation. Perhaps the O.P. wished to represent the byte as 'A'.
Sorry, I meant 0x0A instead of A
Fair enough. Then, as arshajii says, these two values are the same, and entering "0x0A" as a value for a byte is just there for convenience. Java understands this as an integer with value "10". :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.