coreJavare
coreJavare

Reputation: 1469

how 128 int after narrow casting to byte becomes -128

i know in java Byte has 8 bit memory , that is from -128 to 127. I also know the concept of narrowing casting. and int lost some precision. But can some one help me understand the following

    public class PrimitiveTypes {
    public static void main(String[] args) {
        Byte byteVar= (byte) 128;

        System.out.println(byteVar);

    }
}


o/p is -128

please dont tell me because of cycle of 127 it shows -128 . I need the binary arithmatic that happened here. What i able to find from net is java stores integer in 2's complements which is used to store negative no. so from 2's complement

128 becomes 10000000

after flipping 11111111

and adding 1 bit will be

10000000

Question is how this 10000000 becomes -128?

ANS :

Thanks all i got my ans:

I need to convert 2's complement no 10000000 to decimal like

you first check if the number is negative or positive by looking at the sign bit. If it is positive, simply convert it to decimal. If it is negative, make it positive by inverting the bits and adding one. Then, convert the result to decimal. The negative of this number is the value of the original binary.

    Interpret 11011011 as a two's complement binary number, and give its decimal equivalent.
        First, note that the number is negative, since it starts with a 1.
        Change the sign to get the magnitude of the number.
            1   1   0   1   1   0   1   1
        ¬   0   0   1   0   0   1   0   0
        +                               1
            0   0   1   0   0   1   0   1
        Convert the magnitude to decimal: 001001012 = 25_16 = 2×16 + 5 = 37_10.
        Since the original number was negative, the final result is -37. 

So in my case 10000000 becomes 01111111 adding 1 will be 10000000 which is 128 and original no was negative since the first bit is 1 so -128

Upvotes: 3

Views: 1911

Answers (1)

peter.petrov
peter.petrov

Reputation: 39477

In binary the int 128 looks like this.

0000 0000 0000 0000 0000 0000 1000 0000

This is 32 bits, 4 bytes.

When you type cast it to byte you get the last 8 binary digits.

1000 0000

And this turns out to be the binary representation of the byte -128.

So the result is -128 indeed.

All the byte values in binary go like this:

1000 0000  -> - 128
1000 0001  -> - 127
1000 0010  -> - 126
...
1111 1110 -> -2
1111 1111 -> -1
0000 0000 -> 0
0000 0001 -> 1
0000 0010 -> 2
...
0111 1110 -> 126
0111 1111 -> 127

This should make it clear to you.

Your confusion is probably because you're thinking of
1000 0000 as an unsigned byte value. In Java there are
no unsigned bytes. The 1st bit determines the sign.
If there were unsigned bytes (as in some other languages),
this binary value would be indeed 128 and not -128.

Upvotes: 8

Related Questions