Attilah Attilah - 8 months ago 30
C Question

how to loop through the digits of a binary number?

I have a binary number 1011011, how can I loop through all these binary digits one after the other ?

I know how to do this for decimal integers by using modulo and division.

int n = 0x5b; // 1011011

Really you should just do this, hexadecimal in general is much better representation:

printf("%x", n); // this prints "5b"

To get it in binary, (with emphasis on easy understanding) try something like this:

printf("%s", "0b"); // common prefix to denote that binary follows
bool leading = true; // we're processing leading zeroes
// starting with the most significant bit to the least
for (int i = sizeof(n) * CHAR_BIT - 1; i >= 0; --i) {
    int bit = (n >> i) & 1;
    leading |= bit; // if the bit is 1, we are no longer reading leading zeroes
    if (!leading)
        printf("%d", bit);
if (leading) // all zero, so just print 0

// at this point, for n = 0x5b, we'll have printed 0b1011011