Julian - 6 months ago 30

Java Question

I would like to give out the binary code for a number. The following code does indeed give out a "binary code", but he does it in the wrong order. For example, when I would like to print the binary code of 1, it prints "10000000" instead of "00000001". I recognized that multiplying any number by 2 shifts the binary code to the left. For example, the number 5 has the binary code "00000101", and the and the number 10 has the binary code "00001010", and so on. I thought about using this mechanism, but yet, I haven't come to the right idea.

`for (int j = 0; j <= 7; j++) {`

if (x % 2 == 0) {

IO.print(0);

}

else {

IO.print(1);

x = x / 2;

}

}

Answer

```
for (int j = 7; j >= 0; --j) {
if ((x & (1 << j)) != 0) {
IO.print("1");
} else {
IO.print("0");
}
}
```

By doing a bitwise-and (using `&`

) you can mask out all of bits other than the one you are checking.

You generate the "mask" by shifting a number with only bit 0 set to 1 (`1`

) left.

When you do `a & b`

the expression result will have a `1`

bit in every position where it was `1`

in both `a`

and `b`

.