2

I have this hex value 93 which in decimal value should be 147. Since this number is less than 255, it is representable in a byte.

In java I did this

System.out.println((new Integer(1)).byteValue()); //prints 1
System.out.println((new Integer(147)).byteValue()); //prints -109!!! WHY?

What am I not understanding? with integer of 147 instead of printing 147 it prints -109...

2 Answers 2

6

A byte in Java is signed, therefore it represents the values in the range of -128 to 127, as opposed to the unsigned alternative in other languages in the range of 0 to 255. All of Java's integer types are signed, excluding char since since it's used to hold 16-bit Unicode values from 0 to 65535.

The value 147 stored as a byte is represented in binary as:

10010011

Since according to the Oracle docs a byte is: "an 8-bit signed two's complement integer", the signed value becomes:

= -2^7 + 2^4 + 2^1 + 2^0
= -128 + 16 + 2 + 1
= -109
Sign up to request clarification or add additional context in comments.

2 Comments

... except char is an unsigned short
@Bohemian yeah you're right it's an unsigned 16-bit type for holding Unicode. I didn't explain myself well when I put " integer types are signed..." since char obviously is an integer type. I'll fix that, thanks.
3

Because byte is in the range -128:127 (see here). When you call byteValue() you can't get anything out of that range, so it overflows (and starts from the lowest value)

2 Comments

And Java doesn't have unsigned datatypes.
@TimCooper Yes it does: char is an unsigned short

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.