Eva Schopi

Greenhorn

Posts: 2

posted 11 years ago

While reading the book Sun Certified Programmer & Developer for Java 2 I found the following example:

This produces the following output:

I understand x and y but not z. When I use the calculator in Windows and type DeadCafe in hexadecimal mode the decimal result I get is 3 735 931 646. As far as I know an int is capable of representing 2^32 that is 4 294 967 296. So my question is, how do I get the same result as the book?

**class HexTest {**

public static void main (String [] args ) {

int x = 0X0001;

int y = 0x7fffffff;

int z = 0xDeadCafe;

System.out.println("x= " + x +" y= " + y + " z= " + z);

}

}public static void main (String [] args ) {

int x = 0X0001;

int y = 0x7fffffff;

int z = 0xDeadCafe;

System.out.println("x= " + x +" y= " + y + " z= " + z);

}

}

This produces the following output:

**x=1 y=2147483647 z=-559035650**I understand x and y but not z. When I use the calculator in Windows and type DeadCafe in hexadecimal mode the decimal result I get is 3 735 931 646. As far as I know an int is capable of representing 2^32 that is 4 294 967 296. So my question is, how do I get the same result as the book?

posted 11 years ago

an int is 32 bits (if i remember right). that give you 2^32 values, but they are not all positive.

the first bit (leftmost) is used to represent the sign of the number. so, 1/2 of the 2^32 are negative, and 1/2 are non-negative (which includes 0).

search around in this forum for "two's complement", and you see how negative numbers are represented in java.

You calcuator is not limited to 32 bits, so it can display larger numbers.

the first bit (leftmost) is used to represent the sign of the number. so, 1/2 of the 2^32 are negative, and 1/2 are non-negative (which includes 0).

search around in this forum for "two's complement", and you see how negative numbers are represented in java.

You calcuator is not limited to 32 bits, so it can display larger numbers.

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors

Eva Schopi

Greenhorn

Posts: 2

Did you see how Paul cut 87% off of his electric heat bill with 82 watts of micro heaters? |