OK guys, this is my first post in the New Year 2008, I thought of posting it earlier but at last I didn’t. It’s already been so long since I posted so let’s keep everything aside and talk just about what we have for today. ;-)

I was sitting the other day thinking about what to write for a post here. Suddenly
I realized that we have discussed *operations
on matrices*, *arrays*,
and what not but we haven’t had the chance to talk anything about the
most fundamental thing a computer understands. Yeah, Operation on Bits.

Bits can have only two values either ON (1) or OFF (0). In this article, we’ll be discussing about the different operations which can be performed on bits. One thing to note here is, we don’t perform these operation on single bits but rather on a group of bits (byte(s)). So even though Bitwise operators operate on bits its almost always a part of a group (byte, which makes up each data type), it means we can do bitwise operations on any data type.

BTW, the operators that perform operation on bits are called Bitwise Operator and such operations are known as Bitwise Operations

The six bitwise operators are listed below:

& |
AND |

| |
OR |

^ |
XOR |

>> |
Right shift |

<< |
Left shift |

~ |
One’s complement |

For this post we’ll only be discussing &(AND) and | (OR) operators leaving the rest for future posts ;-)

Bitwise AND (&) Operator: First thing, it’s nothing to do with the Logical (&&) operator, both are different.

Now, if you know something about Logic Gates then you might already know about this. For the rest of us, it does an AND mask on bits.

So, suppose if we have two separate bytes having binary values as 00100000 and 00100001 then doing AND operation would give us the following result.

First Byte: |
00100000 00100001 |

Result: |
00100000 |

The truth table for this would be:

First Bit |
Second Bit |
& (AND) |

1 1 0 0 |
1 0 1 0 |
1 0 0 0 |

As the Logic AND Gate does, it takes two bits (from the two separate bytes) and if both of them are ON (1) then only it gives ON (1) in all other cases it gives OFF (0). So starting from the right there is 0&1->0, 0&0->0,…, 1&1->1 and so on.

Bitwise OR (|) Operator: Here again, both OR (||) and Bitwise OR (|) are different.

The following example is sufficient for you all to understand its operation.

First Byte: |
00100000 00100001 |

Result: |
00100001 |

Truth table

First Bit |
Second Bit |
& (OR) |

1 1 0 0 |
1 0 1 0 |
1 1 1 0 |

There won’t be any example program here because to fully understand these operators we need to express data as bits (binary form) and see how the operations change them. Since decimal to binary conversion programs require some bitwise operations that we’ve yet to discuss so I think it’ll be pointless to have such programs now!

P.S. An integer in 32-Bit (Windows) environment is 4 bytes long. Short int
is half of that

8 bits make up one byte.

**Related Articles:**