Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printing the binary representation of a number

Tags:

c++

bit

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);
}
like image 351
User124 Avatar asked Feb 09 '23 02:02

User124


1 Answers

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);
}
like image 93
Zong Avatar answered Feb 20 '23 07:02

Zong