Jan 6, 2009

A bit of bitwise

This is just a little handy structure defining a variable type & a simple operator overload, to get a bit value from a string.

First things first we declare a structure, so:
 ``1234`` ``````struct bin { };``````

Next we need to create a private variable to accept a byte, so we use an unsigned char & let's call it "val":
 ``12`` ``````private: unsigned char val;``````

We need to be able to give the byte a value, so let's create the subroutine to accept the byte & set it to our private variable:
 ``12345`` ``````public: bin(unsigned char v) { val=v; }``````

And last, but not least an operator overload so that we can decide which bit we want:
 ``1234`` ``````bool operator[](unsigned char i) { return (val&(1<>i; }``````

To quickly explain that above, perhaps complex looking, bitwise statement - it takes a number (i) & then finds if that bit is 1 or 0, then it makes the return value equal to that (1 or 0).

So our completed structure is:
 ``123456`` ``````struct bin { private:unsigned char val; public:bin(unsigned char v){val=v;} bool operator[](unsigned char i){return (val&(1<>i;} };``````

Now - how to use this, in this example we will take an unsigned char variable called "a" holding the ASCII value of "a", which is 97 - then find all the bits of it.

 ``12345678910`` ``````int main() { unsigned char a=97; // declare our "a" for(unsigned int c=7;c!=-1;c--) // create a loop to access all the bits { printf("%u",bin(a)[c]); // print out the value of a at bit c. } getchar(); // wait for user input so we can see previous output return 0; }``````

From this we should get "01100001" - 97 in binary.

I hope this is some help to anyone really, & is my first attempt at an article - any feedback or suggestions are welcome.

Chris.