0

I am trying to convert an int to byte.

int i = 128;
byte b = (byte) i;

I know the range of byte if -128 to 127 and the rule of storing an integer to a byte is :

byte_value = int_vale % byte_Range; (I found that in Complete reference Java)

When I apply this to int 128 it should be like this:

byte_value = 128%256 = 128;

But, it actually is : -128

I am not able to understand the actual logic behind this. Please help!!

4 Answers 4

5

Casting to byte doesn't mean int_value % byte_range. It means that only the last 8 significant bits are kept in the byte value. At first that seems to mean the same thing, but bytes are signed.

The int value 128 is the following bits:

00000000 00000000 00000000 10000000

When the last 8 bits are kept, this is the result:

10000000

Now, the most significant bit in the byte is interpreted as -128, not +128 as it was in the int.

The value 128 overflows a byte, and the result is negative because of that most significant bit being set.

Sign up to request clarification or add additional context in comments.

1 Comment

+1, and JLS citation is JLS 5.1.3: "A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits, where n is the number of bits used to represent type T." That (and not Complete Reference to Java or whatever) is the ultimate definition of how the operation works.
1

Logic is simple, Java numbers are always signed in two's complement.

Now a byte has 8 bits and 128 is 10000000. When you do

int i = 128

you end up with:

i == 00000000 00000000 00000000 10000000

When you cast it to a byte you the 24 most significative are truncated, so you end up with

b == 10000000

but a Java byte is signed, and 128 can't be represented, since it overflows and wraps around. So what happens is that the value ends up as 128 - 256 = -128 (that's because of two's complement).

Comments

0

You can simply use the following method:

byteValue()

This returns the value of this Integer as a byte.

You will need to either import Java.lang or type it out as:

Java.lang.Integer.byteValue() 

Comments

0

Bytes are treated as signed values in Java; like you pointed out, the range of a byte is [-128,127]. Adding 1 to 127 flips the sign bit, which means that 127 + 1 = -128.

Comments

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.