| Shift Operators | |||
|---|---|---|---|
| Operation | Operator | Example | Effect |
| left shift | << | 0x0a << 4 ⇒ 0xa0 | Shift left n bits, multiply by 2n |
| logical right shift | >>> | 0xa0 >>> 4
⇒ 0x0a
0xffffffa0 >>> 4 ⇒ 0x7ffffffa |
unsigned shift right n bits, 0 bit fills in on the left, divide by 2n |
| arithmetic right shift | >> | 0xa0 >> 4
⇒ 0x0a
0xffffffa0 >> 4 ⇒ 0xfffffffa |
signed shift right n bits, sign bit fills in on the left, divide by 2n |
| left shift | <<= | x <<= 4 | shorthand for x = x << 4 |
| logical right shift | >>>= | x >>>= 4 | shorthand for x = x >>> 4 |
| arithmetic right shift | >>= | x >>= 4 | shorthand for x = x >> 4 |
int i = -1; i = i >>> 32; // i is -1, not 0 as you might expect. long k = 1; k = k << 65; // k is 2, not 0 as you might expect.As a corollary, shifting left 32 bits does not clear an int. It is a no-op! Be especially careful when working with ints that will eventually be promoted to longs.
byte b = 4; long x = b << 56; // does not work, since shift done modulo 32 and result is int. long x = ( ong)b << 56; // correct
Be especially careful with any calculated shift operands. The shift modulo behavior makes creation of bit selections masks unnecessarily tricky. Suppose you want a general way of extracting bits i through j of an int. An obvious way to do it is to right shift the input by j bits, then & it with a mask containing j-i+1 one bits at the low order end. An obvious way to construct an n-bit right justified mask is (1<<n)-1. This is not correct in Java for n==32. (1 <<32) is 1, not 0, so subtracting 1 from it will result in a zero mask rather than an all-ones mask.
Java works this way for speed since many CPUs work that way.
![]() |
and suggestions to improve this page to Roedy Green : | ||
| Canadian Mind Products | |||
| mindprod.com IP:[65.110.21.43] | |||
| Your face IP:[38.103.63.62] | The information on this page is for non-military use only. | ||
| You are visitor number 11. | Military use includes use by defence contractors. | ||
| You can get a fresh copy of this page from: | or possibly from your local J: drive (Java virtual drive/mindprod.com website mirror) | ||
| http://mindprod.com/jgloss/shift.html | J:\mindprod\jgloss\shift.html | ||