Microcontroller Embedded C Programming Lecture 98| Bitwise AND and bitwise OR

  • Post author:
  • Post category:Blog

 

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
Figure 1. Output

 

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
Figure 2. Output of negative numbers

 

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

 

FastBitLab

The FastBit Embedded Brain Academy uses the power of internet to bring the online courses related to the field of embedded system programming, Real time operating system, Embedded Linux systems, etc at your finger tip with very low cost. Backed with strong experience of industry, we have produced lots of courses with the customer enrolment over 3000+ across 100+ countries.