Hi,
To make use of bitwise operators you must think in binary. In Java there are 3 types of shift operators:
1. << (Shift Left) - Shift all bits left n times, filling with zeros.
2. >> (Shift Right) - Shift all bits right n times, filling with the sign bit.
3. >>> (Shift Unsigned Right) - Shift all bits right n times, filling with zeros.
Lets take some examples:
1. Start with i = 12 and perform i << 4:
Start: 0000 0000 0000 0000 0000 0000 0000 1100
Shift Left#1: 0000 0000 0000 0000 0000 0000 0001 1000
Shift Left#2: 0000 0000 0000 0000 0000 0000 0011 0000
Shift Left#3: 0000 0000 0000 0000 0000 0000 0110 0000
Shift Left#4: 0000 0000 0000 0000 0000 0000 1100 0000
Convert Bin to Dec: 1*128 + 1*64 = 192
2. Start with i = -42 and perform i >> 4:
Start: 42 --> 0000 0000 0000 0000 0000 0000 0010 1010
1's Comp: 1111 1111 1111 1111 1111 1111 1101 0101
2's Comp: 1111 1111 1111 1111 1111 1111 1101 0110
-42: 1111 1111 1111 1111 1111 1111 1101 0110
Shift Right#1: 1111 1111 1111 1111 1111 1111 0110 1011
Shift Right#2: 1111 1111 1111 1111 1111 1111 1011 0101
Shift Right#3: 1111 1111 1111 1111 1111 1111 1101 1010
Shift Right#4: 1111 1111 1111 1111 1111 1111 1110 1101
1's Comp: 0000 0000 0000 0000 0000 0000 0000 0010
2's Comp: 0000 0000 0000 0000 0000 0000 0000 0011
Answer: -3
3. Start with i = -42 and perform i >>> 4:
Start: 1111 1111 1111 1111 1111 1111 1101 0110
Shift Right#1: 0111 1111 1111 1111 1111 1111 1110 1011
Shift Right#2: 0011 1111 1111 1111 1111 1111 1111 0101
Shift Right#3: 0001 1111 1111 1111 1111 1111 1111 1010
Shift Right#4: 0000 1111 1111 1111 1111 1111 1111 1101
Answer: 268435453 (take my
word on this ...)
Regards,
Manfred.