Bit Manipulation in Java

Published by

on

Signed vs Unsigned

Signed variables – Such as signed integers, which can store both positive and negative range of numbers.

Unsigned variables – Such as unsigned integers that will only represent positive numbers.

Both signed and unsigned variables of the same data type have the same range, but unsigned variable can represent larger number than signed one. For example, unsigned byte can represent from 0 to 255, while signed byte can represent from -128 to 127. (128+127=255)

Negative Integers in Java

There are two different ways to represent negative integers in Java.

  1. We can use the MSB(Most Significant Bit) which is the leftmost bit to be used as a signed bit. Setting MSB as 0, we can represent positive integers, while negative integers by setting MSB as 1.
  2. Using two’s complement, we can represent negative integers. To be specific, negative numbers can be represented by flipping all the bits and adding 1. In this case, the first bit can also represent the sign of this integer. For example, 00010100(20) -> 11101011 + 1 -> 11101100(-20)

Bit Shift Operators

Signed Left Shift [ << ]
Signed Left Shift takes the first operand and shift the bit left by the number of the second operand.
ex) 5 << 3 = 40
00000000 00000000 00000000 00000101
-> 00000000 00000000 00000000 00101000

Signed Right Shift [ >> ]
Right Signed Shift moves the first operand to right by the number of second operand. However, using signed right shift preserves the sign, by which filling up the leftmost bit with the previous MSB value.
ex) 4 >> 1 = 2
00000000 00000000 00000000 00000100
-> 00000000 00000000 00000000 00000010
-4 >> 1 = -2
11111111 11111111 11111111 11111100
-> 11111111 11111111 11111111 11111110

Unsigned Right Shift [ >>> ]
Unsigned shift does not consider the sign bit. Instead, it fills the empty bit with 0 s.
ex) 4 >>> 1 = 2
00000000 00000000 00000000 00000100
-> 00000000 00000000 00000000 00000010
-4 >>> 1 = 2147483646
11111111 11111111 11111111 11111100
-> 011111111 11111111 11111111 1111110

Assignment Operators

Bitwise Operators

Reference

Leave a comment