Search code examples
javabitwise-operatorsbitbitwise-and

Java print binary number using bit-wise operator


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

private static void display( int number ){

        System.out.print(number + "\t");        
        int mask = 1 << 31;

        for(int i=1; i<=32; i++) {
            if( (mask & number) != 0 )
                System.out.print(1);
            else
                System.out.print(0);


            if( (i % 4) == 0 )
                System.out.print(" ");

        }

    }

I got it: this works:

/**
     * 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 << 31;

        //loop and print either 1 or 0
        for(int i=31; i>=0; i--) {
            if( ((1 << i)&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();
    }

Solution

  • You forgot to update the mask:

        for(int i=1; i<=32; i++) {
            if( (mask & number) != 0 )
                System.out.print(1);
            else
                System.out.print(0);
    
    
            if( (i % 4) == 0 )
                System.out.print(" ");
    
            mask = mask >> 1;
        }