Wednesday, February 23, 2011

Utility of bitwise operators.

"All the memory addressing in modern machines is byte ordered.", said my Boss, frustrated at my foolishness and lack of comprehensiveness of this fundamental.
What I was trying to do was read bits from the memory as if accessing them out of an array. For instance read the bit-value at position 13, which is actually 5th bit at second byte, considering the buffer I am working on starts with 0. Damn!! It never happened, I was never successful in this endeavor. Why?? The answer to this became clear to me with that single line my boss told me.
This revelation that memory addressing is byte ordered made many concepts fall into place for me. I instantly became clear of the importance of data types like unsigned/signed int/char, big/little endianness.
This may be wierd. But thats how things are many a times, atleast for me. This is something I wasn't aware of. Aware of as in, conscious realization of it. I am sure I have read it many times, thanks to my background.
I became aware of it just today when I was analyzing a hexdump of a frame transferred between two networking layers. I was supposed to program the fate of the packet based on the value in its header field. Thats when it dawned upon me that in order to know what is there in the frame header, I have to use MASK!!
This is where is most of the C functionalities like typecasting, bitwise and (&), or (^), not (!) etc.. , left and right shift operators (<<) (>>), come handy. Below is a code that highlights the basic usage..

#include "stdio.h"
#include "stdlib.h"

int main()
        int i;
        int * an_int = (int *)malloc(sizeof (int));
        *an_int = 255;
        unsigned char * a_char = (unsigned char*)an_int;
        for (i = ((*an_int) & 0); i < ((*an_int) & 4); i++)
                printf("byte wise an_int has at %d[th] position char %d\n",i,*(a_char+i));
        return 0;

No comments:

Post a Comment