System.out.println(
s + ", long: " + l + ", binary: ");
System.out.print(" ");
for(int i = 63; i >= 0; i--)
if(((1L << i) & l) != 0)
System.out.print("1");
else
System.out.print("0");
System.out.println();
views:
107answers:
2You 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;
}
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 1
s). 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
- program with java
- A similar homework assignment
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.