Alex Rivera | Logout

How does bitshifting work in Java?

Asked 2010-07-22T19:55:24.940
63

I have this statement:

Assume the bit value of byte x is 00101011. what is the result of x>>2?

How can I program it and can someone explain me what is doing?

Edit
Report

2 Answers

15

When you shift right 2 bits you drop the 2 least significant bits. So:

x = 00101011

x >> 2

// now (notice the 2 new 0's on the left of the byte)
x = 00001010

This is essentially the same thing as dividing an int by 2, 2 times.

In Java

byte b = (byte) 16;
b = b >> 2;
// prints 4
System.out.println(b);
answered 2010-07-22T19:57:57.850
2

You can use e.g. this API if you would like to see bitString presentation of your numbers. Uncommons Math

Example (in jruby)

bitString = org.uncommons.maths.binary.BitString.new(java.math.BigInteger.new("12").toString(2))
bitString.setBit(1, true)
bitString.toNumber => 14

edit: Changed api link and add a little example

answered 2010-07-22T20:31:20.563

Your Answer