This is a C Program to count the number of bits set to one using bitwise operations.
This C Program Counts the Number of Bits set to One using Bitwise Operations.
Take input from the user and performs bitwise operations as shown in the program below.
Here is source code of the C Program to Count the Number of Bits set to One using Bitwise Operations. 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 set to One using * Bitwise Operations */ #include <stdio.h> int main() { unsigned int number; int count = 0; printf("Enter the unsigned integer:\n"); scanf("%d", &number); while (number != 0) { if ((number & 1) == 1) count++; number = number >> 1; } printf("number of one's are :\n%d\n", count); return 0; }
In this C Program, we are reading the unsigned integer using ‘number’ variable. Using while loop count the number of bits set to one using bitwise operations.
If condition statement is used to check the value which copies a bit to the result if it exists in both operands using Binary AND operator is equal to 1. If the condition is true, then execute the statement and increment the number of bits set to 1 using count variable.
Using Binary Right Shift Operator, the left operand’s value is moved right by the number of bits specified by the right operands and assign the value to ‘number’ variable. Hence we are displaying the output of the program. Print the count of the number of bits set to one using bitwise operations.
$ cc bit2.c $ a.out Enter the unsigned integer: 128 number of one's are : 1 $ a.out Enter the unsigned integer: -127 number of one's are : 26
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 C Books
- Buy Computer Science Books
- Apply for C Internship
- Practice Computer Science MCQs
- Watch Advanced C Programming Videos