Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print all set bits of a negative integer

Tags:

java

bit

 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?

like image 729
JavaDeveloper Avatar asked Dec 24 '22 23:12

JavaDeveloper


1 Answers

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.

like image 106
Jon Skeet Avatar answered Dec 28 '22 06:12

Jon Skeet