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, for 5 the code is "00000101", and the binary code for 10 is "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;
}
}
Aucun commentaire:
Enregistrer un commentaire