Programming machines has always been a difficult task; newer techniques try to solve this by automating the tougher tasks, the low-level handling of the machines. However, some gates have been left open to the older methods, so whenever you wish to use them you are able to do so. At least this applies to C/C++. In this article you'll see how to use bitwise operators in C/C++, and learn why you may want to use them.
Bitwise Operators - Masking Technique and Handy Tricks (Page 4 of 5 )
By now I'm sure you can start figuring out how much you can actually profit from what you've already learned. First let's repeat the integer type constants and how they are formed in C/C++. All natural constants, if they fill in, are int, if not, they are unsigned int. Those that don't fit in here and fit in the long int are represented as long int, while everything else will be put in as an unsigned long int. However we may overwrite this with the following prefixes:
int => 1
u or U -> unsigned int => 1U
l or L -> long int => 1L
ul or UL -> unsigned long int => 1UL.
And there you have four different representations of 1 as constants. Now a question: how do find out in an integer if the n-th bit is 1 or 0? The answer is that we use the masking technique. For this task we'll also use the "&" operator.
The solution comes about in the following fashion:
if(x & (1UL << p))
// here it's going to continue if the bit is 1 // true
// here it's going to enter if the bit is 0 // false
Now the upper code snippet is going to determine whether the p-th bit of the x is 1 or not. However, the upper code will generate 2 at the p-th power, so if we want to print the bit at the p-th position we should negate the number twice. If we negate any non-zero number twice we'll get 1. If it's zero the result will be zero as well:
printf("%d" !!(x & (1UL<<p)));
Using this trick we can easily see whether two integers have the same bit inside at a specific position. If you want to set the p-th bit to 0, you should use bitwise and a negated and shifted constant 1. Here's a quick example:
x &= ~ (1UL<<p);
To do the same but set it to 1 is much easier:
x |= 1UL <<p;
Take a second to think about it. If it helps, don't hesitate to take a sheet of paper and write it down. The simple negation of the p-th bit can be resolved with less effort: