Applicability of bitwise operators : Setting of bits
Bitwise operators in C Exercise:
Write a program to set(make bit state to 1), 4th and 7th-bit position of a given number and print the result.
Now in this exercise, we have to set only the 4th and 7th-bit position of a number. We should not affect any other bit positions. We should keep that in mind.
Let’s analyze how we can set the bits. Let’s take the data.
For this, we have to use a mask value. I use the mask value 1, where the 4th and 7th bits are set.
After that, we have to decide whether you want to use bitwise & operator or bitwise | operator.
What happens if we use bitwise & operator?
00010000 is the result you get.
Here you can see that the output is not correct. We messed up a lot of bits here. So, we messed up with those bits, which we are not supposed to touch. It clearly shows that you cannot use bitwise & operator if your requirement is to set the bits.
That’s why the ‘&’ operator is used to ‘TEST’ not to ‘SET’.
So, you have to use the bitwise | operator in this case.
You have to use the bitwise | operator, and 10010000 is the mask value in this case. So, the mask value turns out to be how much. The mask value = 0x90,
And this mask value you have to bitwise | with the data, and you get this result 10111110. Here you can see that the un-affected data portion, as shown in Figure 1, is not affected at the output. They are safe. So, only 4th and 7th-bit positions are set.
The takeaway from this article is that bitwise ‘&’ is used to ‘TEST’ not to ‘SET’; bitwise ‘|’ is used to ‘SET’ not to ‘TEST’.
Now let’s do the exercise. The program is shown below.
#include<stdio.h> #include<stdint.h> void wait_for_user_input(void); int main(void) { int32_t num1,output; printf("Enter a number:"); scanf("%d",&num1); output = num1 | 0x90; printf("[input] [output] :0x%x 0x%x\n",num1, output); wait_for_user_input(); } void wait_for_user_input(void) { printf("Press enter key to exit this application"); while(getchar() != '\n') { //just read the input buffer and do nothing } getchar(); }
Here, I’m inputting a number, and after that, I create output by using bitwise OR with the mask value. In this case, the mask value is 0x90. After that, I am just printing the numbers in hex format.
Look at the output as shown in Figure 2.
FastBit Embedded Brain Academy Courses
Click here: https://fastbitlab.com/course1