Java Reference
In-Depth Information
byte allBitsOne = 0xFF; // Wrong!!
In fact this results in a compiler error message. The literal 0xFF is 1111 1111 , so what's the beef here?
The beef is that 0xFF is not 1111 1111 at all. The literal 0xFF is type int , so it is the binary value
0000 0000 0000 0000 1111 1111 . This happens to be equivalent to the decimal value 128, which is
outside the range of type byte . The byte value we are looking for, 1111 1111 , is equivalent to the
decimal value -1 so the correct way to initialize allBitsOne to 1s is to write:
byte allBitsOne = 0xFFFFFFFF; // Correct - well done!!
Now the compiler will happily chop off the high order bits to produce the result we are looking for.
Shift Operations
Another mechanism that you have for working with integer variables at the bit level is shifting. You can
shift the bits in an integer to the right or the left. Shifting binary digits right or left can be envisaged as
dividing or multiplying by powers of two. Shifting the binary value of 3, which is 0011, to the left one
bit multiplies it by two. It becomes binary 0110, which is decimal 6. Shifting it to the right by one bit
divides it by 2. It becomes binary 0001, which is 1.
Java has three shift operators:
<<
Shift left, filling with zeros from the right
>>
Shift right, propagating the sign bit from the left
>>>
Shift right, filling with zeros from the left
Search WWH ::




Custom Search