Question

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();
    }
Was it helpful?

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;
    }

OTHER TIPS

The text of the question has been edited numerous times, so it's hard to tell what the question is, but here are some remarks.

On signed vs unsigned shift

One revision of the question contains this line:

int mask = 1 << 31;

One answer suggests that what was missing is this line:

mask = mask >> 1;

This actually won't work, because >> is a signed shift, and would result in the incorrect mask value for this purpose (since emptied bits are filled with 1s). Any negative number would be converted to 32 bits, all 1.

What is needed is the unsigned right shift.

mask >>>= 1;

Note that compound assignment has been used for brevity. Unsigned right shift >>> fills emptied bits with 0. As used here, it ensures that mask will always have only one bit set, which is what is required for this problem.

See also

Similar question


Alternative solution

There's actually a simpler solution to convert a 32-bit int into 32 bits, separated into groups of 4 bits.

static String zeroes(int length) {
    return (length <= 0) ? ""
      : String.format("%0" + length + "d", 0);
}
//...

int num = 8675309;

// convert to binary
String s = Integer.toBinaryString(num);
System.out.println(s);
// prints "100001000101111111101101"

// fill in leading zeroes
s = zeroes(Integer.SIZE - s.length()) + s;
System.out.println(s);
// prints "00000000100001000101111111101101"

s = s.replaceAll("(?!$)(?<=\\G.{4})", " ");
System.out.println("[" + s + "]");
// prints "[0000 0000 1000 0100 0101 1111 1110 1101]"

Even if this is homework, the variety of techniques used here should still be instructional.

See also

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top