I am trying to print out binary number in c however the dilemma i have is that its printing out in the reverse order. I have defined a function to tell me how many bits there are, this way i can work from the last bit back
to get the nth bit i can use
(value >> totalNumberOfBits) & 1;
in a while loop i can run this until the totalNumberOfBits == 0;
as such
while(totalNumberOfBits!= 0){
putchar(n >> totalNumberOfBits)&1;
totalNumberOfBits--;
}
any pointers would be welcome – i think i may be massivley off, i have an approach that prints them number fine backwards but iam trying to find a way of avoiding this
thanks
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:
It is complaining about the
& 1part of your code, which you seem to have accidentally placed outside the parentheses of yourputcharfunction call.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.
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 yournis only 8 bits (and thus out of range). So we move the decrement, and substitute the!=: