Skip to main content

Posts

Showing posts with the label bitwise

Bit manipulation in Java

I have always had a hard time remembering rules of bit manipulation in Java. So, when someone asked this question on Stackoverflow.com , I knew he had to do masking, but I forgot why. I decided to look up bit wise operations on Wikipedia to refresh my memory. However, this time I am also blogging the answer so I don't forget (yet another use of blogging :-) ). There are two types of bit shift operations: arithmetic shift, and logical shift. An arithmetic right shift preserves the sign bit, while logical shifts always insert a zero. Representing -1 as a signed byte we get: 11111111 -1 >> 1 gives us: 11111111 -1 >>> 1 gives us: 01111111 so by this logic (-1 >>> 8) should give us 00000000 which is 0 Well not so: byte b = -1; System.out.println("-1 >>> 8 = " + (b >>> 8)); The output I get is: -1 >> 8 = 16777215 Hmmm. what just happened? Java converted the signed byte into a signed int, and then did an arithmetic right shift of...