Bitwise AND and bitwise OR
In the previous article, we discussed Bitwise operators in ‘C’. In this article let’s do the Bitwise AND and bitwise OR exercise.
Exercise
Write a program which takes 2 integers from the user, computes bitwise &, bitwise |, bitwise ^, and ~ and prints the result.
Here it asks for two numbers, so I use num1 and num2. I’m taking here a signed int of width 32 bits.
Then use printf to enter the two numbers. And use scanf to read the input.
Now we computes bitwise &, bitwise |, bitwise ^, and bitwise ~ and prints the result. So, use printf here.
printf(“Bitwise AND(&) : %d\n”,(num1 & num2));
printf(“Bitwise OR(|): %d\n”,(num1 | num2));
printf(“Bitwise XOR(^): %d\n”,(num1 ^ num2));
printf(“Bitwise NOT(~): %d\n”,(~num1));
The code is shown below.
#include<stdio.h> #include<stdint.h> void wait_for_user_input(void); int main(void) { int32_t num1 , num2; printf("Enter 2 numbers(give space between 2 nos):"); scanf("%d %d",&num1,&num2); printf("Bitwise AND(&) : %d\n",(num1 & num2)); printf("Bitwise OR (|) : %d\n",(num1 | num2)); printf("Bitwise XOR(^) : %d\n",(num1 ^ num2)); printf("Bitwise NOT(~) : %d\n",(~num1)); 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(); }
Let’s run the code and see the output. It is asking Enter two numbers. So, I entered 40 and 30. It is giving the expected output, as shown in Figure 1.
![Bitwise operators C](https://fastbitlab.com/wp-content/uploads/2022/09/Figure-2-1-1024x302.png)
Now let’s try with some negative numbers. It is also giving the correct result. The output is shown in Figure 2.
![Bitwise operators C](https://fastbitlab.com/wp-content/uploads/2022/09/Figure-3-1-1024x301.png)
In the following article, we will understand the applicability of bitwise operations for testing of bits.
FastBit Embedded Brain Academy Courses
Click here: https://fastbitlab.com/course1