## Friday, January 2, 2015

### Bit Manipulation in Java

The >> Operator (Shifts bits right. Inserts duplicate bits of the bit initially at the Most Significant Position)

#1

10000000 00000000 00000000 00001000 >> 3

=

11110000 00000000 00000000 00000001

#2

00000000 00000000 00000000 00001000 >> 3

=

00000000 00000000 00000000 00000001

The >>> Operator (Shifts bits right. Inserts 0s at the left)

#1

10000000 00000000 00000000 00001000 >>> 3

=

00010000 00000000 00000000 00000001

#2

00000000 00000000 00000000 00001000 >>> 3

=

00000000 00000000 00000000 00000001

There is no <<< Operator (that'd be useless)

The << Operator (Shifts bits left, inserts 0s at the right)

#1

10000000 00000000 00000000 00001000 << 3

=

00000000 00000000 00000000 10000000

#2

10000000 00000000 00000000 00010001 << 3

=

00000000 00000000 00000000 01001000

For working with these 32 bit binary string representations, use

`int A = (int)Long.parseLong("10000000000000000000000000001001", 2);`

#Note

```int A = (int)Long.parseLong("10000000000000000000000000001001", 2);
System.out.println(Integer.toBinaryString(A));
int A = Integer.parseInt(   "-0000000000000000000000000001001", 2);
System.out.println(Integer.toBinaryString(A));```

Output:

10000000000000000000000000001001
11111111111111111111111111110111

These are different because the '-' sign does not just set the 32nd bit to 1. It takes the two's complement of the number represented by the rest of the string and then puts a 1 bit at the 32nd position.

Two's complement is calculated by inverting bits and adding 1. (One's complement + Add 1)

11000
inverted bits =  00111
+    1
01000

So in the second case,

0000000000000000000000000001001 (31 bits)
invert =  1111111111111111111111111110110
+1
1111111111111111111111111110111

So the output is
11111111111111111111111111110111 (32 bits)