Links



Technical Discussion

Wednesday, July 13, 2005

 

how? y?

if int i = 24 * 60 * 60 * 1000 * 1000 if we print it gives a value 500654080.
Actually it should give 86400 000 000
How? this is the question?

u are declaring the variable i as int. As u know, in java, int data type will occupy 4 bytes (32 bits). Therefore the range will be as below,

i.e. FROM 10000000000000000000000000000000 TO 01111111111111111111111111111111 (in binary)

i.e. FROM -2147483648 TO +2147483647 (in decimal)

i.e. FROM 0x80000000 TO 0x7FFFFFFF (in hex)

Ok now let me explain the problem.
the value given is 24 * 60 * 60 * 1000 * 1000.

As said it is equal to 86400 000 000.

and in binary it is 1010000011101110101110110000000000000.

obviously it needs 37 bits to store this value into system memory.

but we are assigning it into an int variable, or in other words u are storing the value into 32 bits... so the most signifigant 5 bits will be omitted (i.e. 10100 will be left over). Therefore the value stored wud be

11101110101110110000000000000 (in binary)

i.e. 500654080 (in decimal.) and hence the answer.

In general if the value requires more bits than the number of bits of the data type, then the most significant bits will be truncated (as many number of MSB bits will be truncated as required to make fit into the data type). This is how the behaviour will be with any language.