title: Java print binary number using bit-wise operator
body: <p>Hi I am creating a method that will take a number and print it along with its binary representation. The problems is that my method prints all 0's for any positive number, and all 1's for any negative number</p>
  
  <pre><code>private static void display( int number ){
  
          System.out.print(number + "\t");        
          int mask = 1 &lt;&lt; 31;
  
          for(int i=1; i&lt;=32; i++) {
              if( (mask &amp; number) != 0 )
                  System.out.print(1);
              else
                  System.out.print(0);
  
  
              if( (i % 4) == 0 )
                  System.out.print(" ");
  
          }
  
      }
  </code></pre>
  
  <p>I got it: this works:</p>
  
  <pre><code>/**
       * prints the 32-bit binary representation of a number
       * @param number the number to print
       */
      private static void display( int number ){
          //display number and a tab
          System.out.print(number + "\t");
  
          //shift number 31 bits left
          int mask = 1 &lt;&lt; 31;
  
          //loop and print either 1 or 0
          for(int i=31; i&gt;=0; i--) {
              if( ((1 &lt;&lt; i)&amp;number) != 0)
                  System.out.print(1);
              else
                  System.out.print(0);
  
              //every four bits print a space
              if( (i % 4) == 0 )
                  System.out.print(" ");            
  
          }
          //print new line
          System.out.println();
      }
  </code></pre>