C++ gurus and learners, we program ourselves :P all work is CC licensed

Monday, November 18

Bit Level Manipulation and Programming in C++

C++ is a classical language and it allows us to manipulate bits in much better ways. for starter we will learn 2 kind of bit operators namely bit shift operators

Left shift operator: <<
Right shift operator: >>

The left shift operator shifts all bits to left and left most bit(MSB) is dropped/deleted
similarly the right shift operator shifts all bits to right and LSB(right most bit) is dropped

e.g. binary of 2 will be 00000010 which is when shifted to left becomes 00000100 which in decimal is 4
so it also means that shifting to left multiplies by 2 and shifting to right divides by 2.

void main()
{
int castles = 2;
castles = castles<<1; //this will set castles = 4 i.e. 2x2
castles <<=2; //this will left shift by 2 bits and hence castles is now multiplied by 2 two times so it now becomes 16
//you can experiment for your self with these tricks
//PS these are heavily used for masking purposes and files compression as well

8 comments :