What is wrong with the below code which prints the binary representation of a number?
int a = 65;
for (int i = 0; i < 8; i++) {
cout << ((a >> i) & 1);
}
You're starting at the least significant bit in the number and printing it first. However, whatever you print first is the most significant digit in the typical binary representation.
65 is 01000001
so this is how your loop iterates
01000001
^ Output: 1
01000001
^ Output: 10
01000001
^ Output: 100
...
01000001
^ Output: 10000010
Thus the printed output is in reverse. The simplest fix is to change the order of the loop.
for (int i = 7; i >= 0; i--) {
cout << ((a >> i) & 1);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With