Question

I am missing something while determining how Java stores and retrieves integers. I have the following code

public class Test1 {
    public static void main(String args[]) {

        int a = 100;

        int negateA = (a | 0x80000000);

        System.out.println("Negative A: " + negateA);
        System.out.println("Negative A in HEX: " + Integer.toHexString(negateA));

    }
}

Output:

Negative A: -2147483548
Negative A in HEX: 80000064

From the output, the value in HEX makes sense to me as I am setting the most significant bit of the integer and the rest of the value indicates its decimal value to be 100 which is what I 've set it initially.

I fail to understand why when I print just the integer I get -2147483548

Is there a difference between how java stores the number internally and when its retrieved?

Was it helpful?

Solution

This is not how you obtain a negative number from a positive number! Java uses two's complement.

In order to invert the sign of an int (whether it is initally positive or negative), you do:

~val + 1

Same for longs, bytes and shorts.

The only number for which it doesn't work is 0x80000000, ie Integer.MIN_VALUE, ie -2^31. But that is one of the characteristics of an n-bit two's complement representation: it can represent numbers ranging from -2^(n-1) up to 2^(n-1) - 1.

Let's take 1 as an example:

0x00000001 // i = 1
0xFFFFFFFE // ~i
0xFFFFFFFF // ~i + 1 == -1

0xFFFFFFFF // i = -1
0x00000000 // ~i
0x00000001 // ~i + 1 == 1

OTHER TIPS

The difference is not between "how it is stored" and "when it is retrieved", but it boils down to how the internal representation is interpreted when you convert to decimal and binary. In the first case it is interpreted as twos-complement, which yields your negative number. When you convert it to hex using Integer.toHexString, it is intepreted as an unsigned value. From the javadoc of Integer.toHexString:

The unsigned integer value is the argument plus 23^2 if the argument is negative; otherwise, it is equal to the argument

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top