Linux C Programming Tutorial Part 14 - Bitwise operators practical examples

In one of our earlier articles, we discussed the basics of bitwise operators. I hope you went through that article and are now ready to witness and understand some practical usage examples of these operators. So without further ado, let's begin.

1. Swap values of two variables

I am sure you'd aware of the logic to swap values of two variables. It involves taking a third variable to temporarily store one value and then assign that value to one of the variables (whose original value has already been assigned to the other variable).

For example, if 'a' and 'b' are variables whose values need to be swapped, and 'c' is the temporary variable, then here's how the standard logic goes:

c = a;
a = b;
b = c;

But did you know this whole swapping process can be done through bitwise operators? Yes, that's true, and the logic, in that case, doesn't even require a third variable. Here's the code:

#include <stdio.h>

int main()
{
int a, b;

printf("Enter first number: ");
scanf("%d", &a);

printf("Enter second number: ");
scanf("%d", &b);

printf("As per your input, a = %d, and b = %d", a,b);

a = a ^ b;
b = a ^ b;
a = a ^ b;

printf("\nAfter swapping, a = %d, and b = %d", a,b);


return 0;
}

Here's the output:

Enter first number: 7 
Enter second number: 2
As per your input, a = 7, and b = 2
After swapping, a = 2, and b = 7

2. Check number of binary '1's in a number

Sometimes you may find yourself in a situation wherein you need to count the number of bits set to '1' in a number. You'll be glad to know you can easily do this using bitwise operators. Here's the logic:

#include <stdio.h>

int main()
{
int a, num_of_bits = 0;

printf("Enter a number: ");
scanf("%d", &a);

while(a)
{
if(a & 1)
num_of_bits++;

a = a >> 1;
}

printf("\nNumber of binary 1s in this number is %d", num_of_bits);

return 0;
}

Here's the output:

Enter a number: 5 

Number of binary 1s in this number is 2

3. C program to check if given bit position is 1 or not

Sometimes, especially when working on a code that's related to computer networking (protocols etc), you are required to check whether or not a particular bit position is set to 1 or not. This can easily be done using bitwise operators.

Here's the code:

 #include <stdio.h>

int main()
{
int num, position, temp;

printf("Enter a number: ");
scanf("%d", &num);

printf("Enter the bit position (keeping zero as base index and 31 as max): ");
scanf("%d", &position);

if(((num>>position)&1) == 1)
printf("\nBit at the position is 1");
else
printf("\nBit at the position is 0");

return 0;
}

Here's the output:

Enter a number: 2 
Enter the bit position (keeping zero as base index and 31 as max): 3

Bit at the position is 0

4. Convert decimal number to its binary form

Bitwise operators can also be used to convert a decimal number to its binary form. Here's one logic for it:

#include <stdio.h>

int main()
{
int num, i = 0, temp = 0;
int bin[32] = {0}; // this will initialize all array elements to 0

/* Input number from user */
printf("Enter any number: ");
scanf("%d", &num);

for(i =31; i>=0; i--)
{
if((num & 1) == 1)
{
bin[i] = 1;

num = num>>1;
}

printf("The binary form of the number you entered is: ");

for(i=0; i<32; i++)
{
printf("%d",bin[i]);
}

return 0;
}

Here was the output in my case:

Enter any number: 15 
The binary form of the number you entered is: 00000000000000000000000000001111

Conclusion

The four examples we've shown here should be enough to give you a good idea on how bitwise operators can be used in real-world scenarios. Try these out on your machines, tweak them, and make them do more, or something new. In case of any doubt or query, drop a comment here.

Share this page:

1 Comment(s)

Add comment

Please register in our forum first to comment.

Comments

By: dgrb

I'm not going to discuss your placement of braces ("curly bracket") as that is almost a matter of religous belief.

But you really need to do something about your indentation, which is, to say the least, inconsistent.

The worst example is probably this, from program #3:

if(((num>>position)&1) == 1) printf("\nBit at the position is 1"); else printf("\nBit at the position is 0"); You need to indent the same number of spaces each time (studies have shown that from 2 to 4 are the most effective offsets): here you use 1, in other places you use 2 sometimes 3.Also you should *always* use the brace for any control structure like if, when, for,even when there is only a single statement depending on it: it is all too easy to add another statement which you intend to be part of the if, while, etc but is not because you forgot to add the braces. Trust me, I've been coding in C for over 35 years...