Java Bit Manipulation - What does (num >>= 1) do?

10,668

i >>= 1 is just shorhand for i = i >> 1 in the same way that i += 4 is short for i = i + 4

EDIT: Specifically, those are both examples of compound assignment operators.

Share:
10,668

Related videos on Youtube

Algo Learner
Author by

Algo Learner

Updated on June 04, 2022

Comments

  • Algo Learner
    Algo Learner almost 2 years

    I was looking at some code that outputs a number to the binary form with prepended 0s.

        byte number = 48;
        int i = 256; //max number * 2
        while( (i >>= 1) > 0) {
            System.out.print(((number & i) != 0 ? "1" : "0"));
        }
    

    and didn't understand what the i >>= 1 does. I know that i >> 1 shifts to the right by 1 bit but didn't understand what the = does and as far as I know, it is not possible to do a search for ">>=" to find out what it means.

  • Lawrence Dol
    Lawrence Dol about 13 years
    And, specifically, it's a sign-extending shift.
  • yasouser
    yasouser about 13 years
    Mathematically right shifting a number by 1 is equivalent to the dividing the number by 2.

Related