Bit shift operation ?

i am trying to understand bit shift operand which are bit shift right and bit shift left. And bit masking ?
I have been searching on web but.
Can you please explain briefly ?

And please some sample code.
Thanks
Bit shifting operations will shift bits in the specified direction adding 0s as padding. For example consider right bit shift operation.

1
2
3
4
5
std::cout<< (8 >> 1);
/*
this means we are going to shift 01000 by 1 bit to the right
so, move all bits one position to the right and add 0 as padding
*/


this will result into

4
/*00100*/


Every bit (the 1) was moved one position to the right, and a 0 has been added in place of discarded bits. If you pay attention at the result, you see that it was in fact divided by 2. Right bit shifting will divide your number by 2^n, where n is the number of bits you shift to the right.

Now, left shifting is the same operation, but in the opposite direction. You move each bit to the left and add 0s as padding


1
2
3
4
5
std::cout<< (8 << 1);
/*
this means we are going to shift 01000 by 1 bit to the left
so, move all bits one position to the right and add 0 as padding
*/


this will result into

16
/*10000*/


As you can see, we moved the 1 to the left by 1 position and our number doubled. Right shifting will multiply our number by 2^n, where n is the number of bits we shifted to the left.

Bit masking is transforming a part of a number's bits into either all 0s or all 1s. This is done by doing bit operations on your number.


1001000
1111000

Here we masked the first nibble of the number into 1s

Topic archived. No new replies allowed.