Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

hurrf durf

Name: Anonymous 2010-01-15 11:31

I suck at bit twiddling, somebody please explain why this works.

// to-binary-bitops.cpp  Print binary representation of ints
// Fred Swartz  - 2001-09-04

#include <iostream>
using namespace std;

int main() {
    int n;
    while (cin >> n) {
        cout << "decimal: " << n << endl;

        // print binary with leading zeros
        cout << "binary : ";
        for (int i=31; i>=0; i--) {
            int bit = ((n >> i) & 1);
            cout << bit;
        }
        cout << endl;
    }//end loop
    return 0;
}//end main

Name: Anonymous 2010-01-15 11:43

Say you have a 4-bit number, 0101. It's ugly to explain what's going on in words alone, so here's a diagram.


>>>0 101 (n >> 3) ("0" printed)
>>01 01  (n >> 2) ("1" printed)
>010 1   (n >> 1) ("0" printed)
0101     (n >> 0) ("1" printed)
   ^


The caret sits under the first bit of the number in memory as it's shifted by a decreasing number of bits, and the & isolates the current bit by clearing the remaining bits.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List