When I cast a long into an byte, and the long is larger than the byte, can someone show me what is happening in the background? long l = 130; byte b = (byte)l; I know that the byte is widened to an integer type, but not sure what else is happening to get the answer -126. Can someone tell me if this is right? 130 in binary = 0000 0000 0000 0000 0000 0000 1000 0010 what happens next?
Thanks, leo
Thomas Paul
mister krabs
Ranch Hand
Joined: May 05, 2000
Posts: 13974
posted
0
A byte is 8 bits so only the last 8 bits are put in the byte: 1000 0010 Since it starts with a 1 we know it is a negative number. Do 2's compliment and you get 126.
In case "The Saint" didn't clear that all up for you, the compiler will simply truncate your long value to make it fit into a byte's 8-bit size. Since a long is a signed 32-bit integral type and your byte is a sad 8-bit integral type, it just chops off the left-most 24 bits, leaving you with the 1000 0010 binary byte. Which, as the saint so kindly noted comes out to your -126 after a few minutes of cursing those days you slept in the back of your undergrad CS classes after you do the 2s complement. To correct your post then ... the byte is never really "widened" to an int primitive. The truncated long value is actually placed into the byte.
Priyank Patel
Greenhorn
Joined: May 17, 2003
Posts: 7
posted
0
Originally posted by Nathaniel Stoddard: In case "The Saint" didn't clear that all up for you, the compiler will simply truncate your long value to make it fit into a byte's 8-bit size. Since a long is a signed 32-bit integral type and your byte is a sad 8-bit integral type, it just chops off the left-most 24 bits, leaving you with the 1000 0010 binary byte. Which, as the saint so kindly noted comes out to your -126 after a few minutes of cursing those days you slept in the back of your undergrad CS classes after you do the 2s complement. To correct your post then ... the byte is never really "widened" to an int primitive. The truncated long value is actually placed into the byte.
Just to Correct this post Long is 64 bit Integral Type Not 32 bit Integral Priyank