while (totalNumberOfBits != 0) {
putchar(n >> totalNumberOfBits) & 1;
totalNumberOfBits--;
}
Okay, you're code was pretty close (and was in fact already printing out the bits in the correct order), however there were 3 small errors. Firstly, when compiling Visual Studio gives me the following warning:
warning C4552: '&' : operator has no effect; expected operator with side-effect
It is complaining about the & 1
part of your code, which you seem to have accidentally placed outside the parentheses of your putchar
function call.
while (totalNumberOfBits != 0) {
putchar((n >> totalNumberOfBits) & 1);
totalNumberOfBits--;
}
The second error is that, while it is now correctly printing bits, you are printing \0 and \1 characters. \0 will not show in the console, and \1 will most likely look like a smiley, so let's fix that as well.
while (totalNumberOfBits != 0) {
putchar(((n >> totalNumberOfBits) & 1) ? '1' : '0');
totalNumberOfBits--;
}
This is very close now, there is just one small mistake remaining. Because of the check your while loop performs, and the place where you decrement totalNumberOfBits
, you never check the bit for 2^0, while you do check 2^8 even if your n
is only 8 bits (and thus out of range). So we move the decrement, and substitute the !=
:
while (--totalNumberOfBits >= 0) {
putchar(((n >> totalNumberOfBits) & 1) ? '1' : '0');
}