Author | Topic: shift operators |
raja pratap greenhorn |
posted April 07, 2000 04:25 AM
It is given in the javaranch roundup game, Assume that the bit pattern of the byte x is 10110001.What will be the sign of x after x>>2? It is given negative?How come?? I think before performing the shift operation, byte will be converted to int and then this operation will be performed.So I think the answer should be positive.And one more thing, I tried to compile it but it didn't compile because the value represented by the bit pattern above will not fit into a byte range... Help me.....
|
Java Nut unregistered |
posted April 07, 2000 05:16 AM
Of course, >> is the unsigned right shift operator. When you assign a byte to an int in the compiler, does it not maintain it's sign? byte b = -1; int i = (int)b; Of course it does! So your answer will still be negative.
|
maha anna bartender |
posted April 07, 2000 10:46 AM
Raja, In java, byte primitive has 8 bits. Out of these 8 bits, the MSB (most significant bit) is used for sign of the byte val. IF it is 1 it indicates it is a negative val. All >> , >>>, << operationa in JAva are done using either int/long primitives only. Anything below int are promoted to int anf then the shifing operation done. SO when converting a byte to int , the MSB of the byte is filled for the expanded bits in int primitive. Since >> is signed right shift all shifted bits in left side of the int are filled with the already existing sign-bit which is now 1 . So the result will have the negative sign carried out. regds maha anna
|
raja pratap greenhorn |
posted April 07, 2000 10:11 PM
Thanks alot ....
|
| | |