Microcontroller Embedded C Programming Lecture 100| Finding a number even or odd using testing of bits

  • Post author:
  • Post category:Blog

 

Find a number even or odd using testing of bits

 

 

Exercise:

Write the program to find a number even or odd using testing of bits using the bitwise AND (&) operator .

 

Code:

#include<stdio.h>
#include<stdint.h>

void wait_for_user_input(void);

int main(void)
{
    int32_t num1;
    printf("Enter a number:");
    scanf("%d",&num1);

    if(num1 & 1){
          printf("%d is odd number\n",num1);
    }else{
          printf("%d is even number\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();

}

 

Here a variable is num1. The num1 datatype is int32_t. The number an integer because even or odd refers to only integers, whether a negative or positive integer. That’s why I created a signed variable.

Now let’s do our logic. if(num1 & 1) [1 is mask value]. So, if this expression is non-zero, then it prints it as an odd number; else, it is an even number. That’s all you have to do.

 

Let’s see the output. Here it asks to Enter a number. I entered -244. It shows that -244 is an even number, as shown in Figure 1. 

Bitwise Operators - Find a number even or odd using testing of bits
Figure 1. Output

 

I entered the number 0, it shows that 0 is an even number( as shown in Figure 2).

Bitwise Operators- Find a number even or odd using testing of bits
Figure 2. Output

 

I entered the number 445.  It shows that 445 is an odd number, as shown in Figure 3.  

Bitwise Operators
Figure 3. Output

 

So, that’s actually how you use the bitwise AND operator to test the bits. When we do coding for our target hardware with GPIOs and with the keypads and all, we’ll be making of this AND operator. 

Before going to the following article, you try to do this exercise on the setting of bits. 

 

Exercise:

Write a program to set(make bit state to 1), 4th and 7th-bit position of a given number and print the result.

First, you take one number, then write the binary format on the paper, then try to make the 4th and 7th-bit position as 1 of that number, then recalculate the value, and then write a program to compare your calculation. 

 

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.

Leave a Reply