Handeling Unsigned Integer in Java

In programming language like C and C++ we have signed and unsigned integer(int) but java does not support unsigned, i.e. Positive integer only. Actually java designer felt that unsigned was used only to specify the behavior of high order bit (sign bit), which is unnecessary.

To replace the use of unsigned concept in java, a bitwise operator is used; that is “unsigned shift integer”.

We do have two right shift operator in Java programming, they are:

> Right Shift
> Unsigned Right Shift

The right shift (>>) operator automatically fills the high-order bit with it’s previous contents each times shift occurs, which preserve the sign of the value. Which we can observe in below example.

a) With Negative number

public class UnSign {
public static void main(String[] args) {
int data = -16;
//11111111111111111111111111110000
System.out.println(“Unsigned Shift By 2 : “+ (data >> 2));
//11111111111111111111111111111100
System.out.println(“Unsigned Shift By 31 : “+ (data >> 31));
//11111111111111111111111111111111
}
}

Output:
Unsigned Shift By 2 : -536870912
Unsigned Shift By 31 : -1

b) With Positive number

public class UnSign {
public static void main(String[] args) {
int data = 16;
//0000000000000000000000000010000
System.out.println(“Unsigned Shift By 2 : “+ (data >> 2));
//00000000000000000000000000000100
System.out.println(“Unsigned Shift By 31 : “+ (data >> 31));
//00000000000000000000000000000000
}
}

Output:
Unsigned Shift By 2 : 4
Unsigned Shift By 31 : 0

Unlike Right Shift operator, Unsigned Right Shift (>>>) operator fills the high-order bit with Zero (0), which preserve it to behaves like unsigned. Which is clearly tried to explain in below example.

a) With negetive number

public class UnSign {
public static void main(String[] args) {
int data = -16;
//11111111111111111111111111110000
System.out.println(“Unsigned Shift By 2 : “+ (data >>> 2));
//00111111111111111111111111111100
System.out.println(“Unsigned Shift By 31 : “+ (data >>> 31));
//00000000000000000000000000000001
}
}

Output:
Unsigned Shift By 2 : 1073741820
Unsigned Shift By 31 : 1

b) With Positive number

public class UnSign {
public static void main(String[] args) {
int data = 16;
//0000000000000000000000000010000
System.out.println(“Unsigned Shift By 2 : “+ (data >>> 2));
//00000000000000000000000000000100
System.out.println(“Unsigned Shift By 31 : “+ (data >>> 31));
//00000000000000000000000000000000
}
}

Output:
Unsigned Shift By 2 : 4
Unsigned Shift By 31 : 0