This is a C Program to count the number of bits needed to be flipped to integer X to generate integer Y.
This C Program counts the number of bits needed to be flipped to integer X to generate integer Y.
Take input from the user and performs binary right shift operation as shown in the program below.
Here is source code of the C Program to count the number of bits needed to be flipped to integer X to generate integer Y. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/* * C Program to Count the Number of Bits needed to be Flipped * to Integer X to Generate Integer Y */ #include <stdio.h> #include <stdlib.h> #define NUM_BITS_INT (sizeof(int)*8) void main() { int n, m, i, count = 0, a, b; printf("Enter the number\n"); scanf("%d", &n); printf("Enter another number\n"); scanf("%d", &m); for (i = NUM_BITS_INT-1;i >= 0;i--) { a = (n >> i)& 1; b = (m >> i)& 1; if (a != b) count++; } printf("flip count = %d\n", count); }
In this C Program, we are reading the two integer values using ‘n’ and ‘m’ variables respectively. For loop is used to count the number of bits needed to be flipped to integer X to generate integer Y.
Binary Right shift operation, the left operand’s value is moved right by the number of bits specified by the right operands then copy a bit to the result if it exists in both operands.
If condition statement is used to check that the value of bit is not equal. If the condition is true, then execute the statement and print the number of bits to be flipped to integer X to generate integer Y.
$ cc flip.c $ a.out Enter the number 127 Enter another number 125 flip count = 1 $ a.out Enter the number 127 Enter another number 128 flip count = 8 $ a.out Enter the number 42 Enter another number 21 flip count = 6
Sanfoundry Global Education & Learning Series – 1000 C Programs.
Here’s the list of Best Books in C Programming, Data-Structures and Algorithms
- Get Free Certificate of Merit in C Programming
- Participate in C Programming Certification Contest
- Become a Top Ranker in C Programming
- Take C Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Buy Computer Science Books
- Watch Advanced C Programming Videos
- Apply for C Internship
- Practice BCA MCQs
- Buy C Books