Signed vs unsigned shift

suggest change

In Java, all number primitives are signed. For example, an int always represents values from -2^31 to 2^31 - 1, keeping the first bit to sign the value: 1 for a negative value, 0 for a positive value.

Basic shift operators >> and << are signed operators. They will conserve the sign of the value.

But it is common for programmers to use numbers to store unsigned values. For an int, it means shifting the range to [0, 2^32 - 1], to have twice as many values as a signed int.

For those power users, the sign bit has no meaning. That’s why Java added >>>, an unsigned right-shift operator, which shifts in a zero instead of copying the sign bit.

initial value:               4 (                                100)
signed left-shift: 4 << 1               8 (                               1000)
signed right-shift: 4 >> 1               2 (                                 10)
unsigned right-shift: 4 >>> 1               2 (                                 10)
initial value:              -4 (   11111111111111111111111111111100)
signed left-shift: -4 << 1              -8 (   11111111111111111111111111111000)
signed right-shift: -4 >> 1              -2 (   11111111111111111111111111111110)
unsigned right-shift: -4 >>> 1      2147483646 (    1111111111111111111111111111110)

Why is there no <<< ?

This comes from the intended definition of right-shift. As it fills the emptied places on the left, there is no decision to take regarding the sign bit. As a consequence, there is no need for 2 different operators.

See this question for a more detailed answer.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents