Signed vs unsigned shift

suggest change

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

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 much value as with a signed int.

For those power users, the bit for sign as no meaning. That’s why Java added >>>, a left-shift operator, disregarding that 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 are no decision to take regarding the bit of sign. As a consequence, there is no need for 2 different operators.

See this question for a more detailled answer.

Feedback about page:

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


Bit Manipulation:
* Signed vs unsigned shift

Table Of Contents
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
41 Scanner
54 Bit Manipulation
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap