How to print all set bits of a negative integer

 while (n != 0) {
      System.out.print(n & 1);
      n  = n >> 1;
 }

The above code in Java leads to an infinite loop, if n = -1.

How do I get it to print negative integers?

Jon Skeet
people
quotationmark

The >> operator is a "sign-extended" right-shift operator, which means that if the top bit in the original value is set, the bits that are "shifted in" are 1. That keeps the sign of the result the same, basically.

You want the >>> operator (the unsigned right shift operator), which always "shifts in" 0 bits, even if the top bit was 1.

See JLS section 15.19 or the Java tutorial for more details.

people

See more on this question at Stackoverflow