Hi, I came across this question on one of the harder mock exams and fail to understand the given result. (I'm sitting the SCJP2 exam next week!) Question: (byte)0x81 >> 2 Given Answer: 0xFFFF FFE0 I converted 0x81 to Binary (is this correct value?) 0000 1000 0000 0001 Then if this is cast to a byte don't the first 16 bits get thrown away and we are left with the binary value 0000 0001? (This is the part where I need clarification). Because if I invoke the right shift operator on this, then the answer is definatly not negative. But somehow, casting 0x81 to a byte makes the value negative? Can someone give me an explanation? Thanks a mil, Caragh
0x81 in binary is 00000000 00000000 0000000 10000001 and not what you wrote. Remember that when writing numbers in hexadecimal each digit is represented by 4 bits. then casted to byte only the eight low-level bytes are kept: (byte)0x81 gives 10000001 Then sign-shifted 2 steps to the rigth it gives 11100000 and then the result is probably converted to an int which yields 11111111 11111111 11111111 11100000 (0xFFFFFFE0) which is obviously a negative number HIH [ February 07, 2002: Message edited by: Valentin Crettaz ]
Just to fine tune the explanation, the left hand operand will be converted to either an int or a long before the bits are shifted. So the initial cast to byte is only temporary. Actually, in this example the hex literal is already a byte, so casting it to a byte does nothing, however it could be a different case if say the initial value had been (byte)0x800F. This would have basically lost the upper 8 bits of this negative number, and resulted in a positive 8 bit number. But what you had originally was (byte)0x81, which results in a byte value of 0x81, (-127 decimal) which then gets widened to an int before the bit shift occurs. 11111111 11111111 11111111 100000001 = 0xFFFFFF81 which still equals -127.
The result is an int value. [ February 07, 2002: Message edited by: Rob Ross ]
Joined: Aug 26, 2001
Rob is right! Thanks for the fine tuning by the way )
Just so I have this straight when a primitive like byte or short is widened to an int it will fill in to the left with the whatever the signed bit is? So if it's negative it will fill in with 1s and if positive it will fill with 0s. I knew about filling in with 0s but didn't even think about it being negative in which case it fills in to the left with 1s ?
Joined: Jan 07, 2002
Yes Rick, that is correct. If it didn't do that, then every time it widened a negative number, it would end up being a totally different positive number, and that wouldn't be very useful!