This is a C Program to check if all the bits of a given integer is one.
This C Program to check if all the bits of a given integer is one.
Take input from the user and performs bits operations as shown in the program below.
Here is source code of the C Program to check if all the bits of a given integer is one. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/* * C Program to check if all the bits of a given integer is one(1) */ #include <stdio.h> #include <stdlib.h> int main () { int num = 0, count = 0, n = 0, i = 0; printf ("\nEnter the number : "); scanf ("%d", &num); n = num; if (num == 0) { printf ("\nFALSE : ALL BITS ARE NOT SET\n"); exit (0); } while (n) { count ++; n = n >> 1; } for (i = 0; i < count; i++) { if (((num >> i) & 1) == 1) { continue; } else { printf ("\nFALSE : ALL BITS ARE NOT SET\n"); exit (0); } } printf ("\nTRUE : ALL BITS ARE SET\n"); return 0; }
1. In this C program, we are reading the number using ‘num’ variable. Take the input number from the user and make a copy of the number to n.
2. If the number given is zero we just print NOT SET and exit.
3. While loop is used to count the number of bits. n = n >> 1; it performs right shift by 1 bit. Traverse through each bit. continue if the bit is set else print NOT SET and exit.
4. (num >> n) & 1; is used to retrieve the nth bit from the number num.
5. For loop is used to check whether all bits are set. If all bits are set then print “ALL BITS ARE SET” and return.
Test case 1 – Here, the entered number is 0.
$ cc bit22.c $ a.out Enter the number : 0 FALSE : ALL BITS ARE NOT SET
Test case 2 – Here, the entered number is 5.
$ cc bit22.c $ a.out Enter the number : 5 FALSE : ALL BITS ARE NOT SET
Test case 3 – Here, the entered number is 7.
$ cc bit22.c $ a.out Enter the number : 7 TRUE : ALL BITS ARE SET
Test case 4 – Here, the entered number is 127.
$ cc bit22.c $ a.out Enter the number : 127 TRUE : ALL BITS ARE SET
Sanfoundry Global Education & Learning Series – 1000 C Programs.
Here’s the list of Best Books in C Programming, Data-Structures and Algorithms
- Check Computer Science Books
- Apply for Computer Science Internship
- Check C Books
- Watch Advanced C Programming Videos
- Practice BCA MCQs