Win a copy of Design for the Mind this week in the Design forum!

# cast between long and int.

james gong
Ranch Hand
Posts: 48
can you automataiclly convert a long primitive to a int ,if the value of the long is samll enough to fit the int?

sandip karmarkar
Greenhorn
Posts: 26
Hi
You can carry out narrowing of conversion if range of the variable is not a problem. If range of long variable for conversion is within range of interger then narrowing of conversion is possible.
Regards
Sandip

Dave Vick
Ranch Hand
Posts: 3244
James
If by automatically convert you mean without a cast then no you can't do it (not from long to int anyway. You can do it by casting but may lose information when the leftmost bits of the value being cast get cut off. Going from a long to an int the 32 most significant bits would get truncated. For example the largest long you can have is -9223372036854775807. This is
01111111 11111111 11111111 11111111 11111111 11111111 11111111 11111111 in binary. Casting this to an int would result in the left most 32 bits getting chopped so it would be: 11111111 11111111 11111111 11111111 or -1 in decimal.
run this to see it in action:
hope that helps
Dave
[This message has been edited by Dave Vick (edited June 26, 2001).]