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.
I entered the number 0, it shows that 0 is an even number( as shown in Figure 2).
I entered the number 445. It shows that 445 is an odd number, as shown in Figure 3.
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