0

I am trying to shift the number 1 to the right.

So originally, the bit mask should be:

1

Then, the bit mask should be:

01

Below is my code:

int bitmask = 1;
bitmask >>= 1;
System.out.println(Integer.toBinaryString(bitmask));

The output however, is just:

0
Adam Lee
  • 436
  • 1
  • 14
  • 49
  • 1
    `1` and `01` are the exact same number, just like in decimals. When you shift to the right, the right most bit is shifted out of the binary number, so it disappears. – Ivar Oct 23 '20 at 00:35
  • 1
    But shifting right by 1 has the same effect as dividing by 2. Integer division discards fractions, so 1/2 is zero int. – Bohemian Oct 23 '20 at 00:41

3 Answers3

2

Maybe we are misunderstanding about how bitshifting works. When doing a right shift, the least significant bit (1) is lost.

1 in binary is 0b01 already. This is equivalent with 0b00000001. Shifting this right results in 0b00.

Try this instead and see that bitshifting works.

public class MyClass {
    public static void main(String args[]) {
        int bitmask = 0b10;
        System.out.println(Integer.toBinaryString(bitmask));
        bitmask >>= 1;
        System.out.println(Integer.toBinaryString(bitmask));
    }
}

Output

10
1
teddy
  • 518
  • 2
  • 14
1

The bitmask 1 and 01 or 001 or 0...1 are all the same. When you do a right shift the least significant digit (1 in your case) is lost, so the output is correct.

tonyfarney
  • 300
  • 3
  • 14
0

Please try the following

public static void main(String[] args) {
    int bitmask = 1;
    bitmask >>= 1;
    int binaryval = Integer.parseInt(Integer.toBinaryString(bitmask));
    String binary = String.format("%2s", Integer.toString(1, 2)).replace(' ', '0');
    System.out.println(binary);
}

The Javadoc for Integer.toBinaryString(int) says (in part),

This value is converted to a string of ASCII digits in binary (base 2) with no extra leading 0s. Reference is made here

DarrenChand
  • 116
  • 13