Bitwise Arithmetic – 1

One of the more important concepts to maintain in C programming has got to be it’s focus on creating fast and terse code to do amazing things. Most of the programmers I have worked with have completely brushed over bitwise arithmetic in their careers on the grounds that they are never going to use it. As with calculus, bitwise arithmetic gives us all a different frame of reference, in terms of being able to solve problems.

When beginning work on bitwise arithmetic, the first thing that has to be done is to learn the indexing of the bits you are playing with, and it will lead to some more interesting problems, and explain why you may have heard of terms like Big or Little Endian.

#include "stdio.h"

void printBits(int i)

int main(int argc, char **argv)
{
    printBits(0);
    printBits(1);
    printBits(1<<1);
    printBits(1<<2);
    printBits(1<<3);
    printBits(1<<4);
}

void printBits(int i)
{
    printf("%dt", i);

    for (int ndx = 0; ndx < 32; ndx++)
    {
    if (1 << ndx & i)
        printf("1");
    else
        printf("0");
    }
    printf("n");
}

Running this program output the following on my machine. Your mileage may vary.

0   00000000000000000000000000000000
1   10000000000000000000000000000000
2   01000000000000000000000000000000
4   00100000000000000000000000000000
8   00010000000000000000000000000000
16  00001000000000000000000000000000

I recommend that if you are interested in playing with bits you take some time to nose around in this function. It may be more interesting than you think.