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:
1
2
3
4
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":
1
2
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:
1
2
3
4
5
public:
bin(unsigned char v)
{
val=v;
}

And last, but not least an operator overload so that we can decide which bit we want:
1
2
3
4
bool operator[](unsigned char i)
{
return (val&(1<<i))>>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:
1
2
3
4
5
6
struct bin
{
private:unsigned char val;
public:bin(unsigned char v){val=v;}
bool operator[](unsigned char i){return (val&(1<<i))>>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.

1
2
3
4
5
6
7
8
9
10
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.
I think you might want to upgrade to C++ iostream, etc instead of printf() etc, since if you are using classes then you have to be using C++.
Last edited on
You don't need the right shift in the index operator.

And the index should probably be an int rather than a char as it's more efficient. The char will be pushed as an int and used as a char in the called function.

1
2
3
4
bool operator[](unsigned int i)
{
    return (val & (1<<i)) != 0;
}


Thanks for posting the article.
Oddly enough firedraco I used to always use C++ iostream, I just seem to find the << & >> used as input / output slightly annoying =P
Thanks kbw, I will take into account the unsigned int instead of char - I use the right shift so that the function always returns a 1 or a 0.
Thanks for all feedback, I might do another bitwise article sometime ;)
Topic archived. No new replies allowed.