-3
class Example{
    public static void main(String args[]){
        int x;
        byte b;
        x=Short.MAX_VALUE;
        b=(byte)x;
        System.out.println(b);
        
        x=Short.MIN_VALUE;
        b=(byte)x;
        System.out.println(b);

    }
}

This code gives outputs as -1 and 0 respectively. Aren't they supposed to be 127 and -128 respectively because the it is the range that a byte variable can hold. I am new to programming so I'm having issues in conversions.

1 Answers1

4

Computers work in binary. They store things in bits. They also use something called two's complement. A bit is a 0 or 1.

When you count, you go 0 1 2 3 4 5 6 7 8 9 10. 10 is weird. Why did 'we' decide to switch to two symbols, re-using earlier numbers? Because we have 10 fingers. Computers have, effectively, 2. They count the same way, just, their second number (what 'we' call '2') is where the computer decides to reuse digits, just like we don't have a single digit for '10'. Thus, computers go 0 1 10 11 100 101 110 111 1000, etcetera.

Bits just store 0 or 1, so there is no room for - either; you'd have to encode that as a 0 or 1.

two's complement is a fancypants way of storing negative numbers. The rule is: flip every bit, then add 1. So, Given a byte (8 bits), to turn, say, the number '3' (which, in binary is 0000 0101) into -3, flip every bit and add 1: 1111 1010, then add one: 1111 1011.

This 'weird' system has the very interesting property that the operation you have to do to the bits to do arithmetic (specifically, adding and subtracting) gets to not give a crap if it's signed or unsigned. The computer just knows you have a byte and the bits in this byte are 1111 1011. That's all the computer knows. That, if you print it, it prints '-3'? That's a human convenience. The reason that prints -3 is solely because java defined that bytes are to be considered 'signed'. Note that 1111 1011 also means 253. It's the same number. Try it:

byte b = (byte) 253;
System.out.println(b); // prints -3

This means that the largest short is 0111 1111 1111 1111. Why? Because if the 'highest' (leftmost) bit was a 1, it'd have been a negative number.

If you make that a byte, you just lop off the top 8 bits, and just leave 1111 1111. That's a negative number (first bit is a 1, so, negative). To turn it into a positive number, that two's complement rule works both ways. flip all bits and 1. flip all bits makes that 0000 0000, add 1: 0000 0001. Which is 1. So, 1111 1111 is -1, and that's why your first println prints -1.

Similarly, Short.MIN_VALUE is -32768. In bits, that's 1000 0000 0000 0000. Turn that to a byte using (byte) thatNumber, and that just lops off all the bits except the rightmost 8 bits, which are all zeroes.

You can search the web (e.g. wikipedia) for two's complement for more information.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72