Q:

C program to check if all the bits of a given integer is one (1)

0

C program to check if all the bits of a given integer is one (1)

 Write a C Program to check if all the bits of a given integer is one (1).

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Pre-requisite: Input number n

Algorithm:

1)  Do Bitwise AND with n and 1. 
    n & 1
    
    let n be a7a6a5a4a3a2a1a0
    1->00000001
    So doing bitwise AND (refer to published article on bitwise operators) 
    will result in all bits 0 except the LSB which will be a0. 
    If a0 is 0 then the all bits are not set
    Thus,
    IF
        n & 1 ==0
        Print that all bits are not same
    ELSE
        Right shift n by 1
        n=n>>1
    END IF-ELSE

2)  IF n==0
        Print that all bits are set
    ELSE
        REPEAT step 1

Example with Explanation:

Checking for 12
12-> 00001100

So first iteration:
n=12 //00001100
n & 1 ==0 
so print that all bits are not set

Checking for 7
7->00000111

So first iteration:
n=7 //00000111
n & 1 =1
n=n>>1 (n=3) //00000011

So second iteration:
n=3 //00000011
n & 1 =1
n=n>>1 (n=1) //00000001

So third iteration:
n=1 //00000001
n & 1 =1
n=n>>1 (n=0) //00000000

So, All bits are set
 

C implementation

#include <stdio.h>

int main()
{
	unsigned int n;
	printf("enter the integer\n");
	scanf("%d",&n);

	while(n>0){
		int temp=n&1;
		if(temp == 0){ //if any bit not set
			printf("all bits are not set\n");
			return 0;
		}
		n=n>>1; //right shift operator
	}

	printf("all bits are set ");
	printf("in its binary representation\n");

	return 0;
}

Output

First run:
enter the integer
12
all bits are not set

Second run:
enter the integer
7
all bits are set in its binary representation

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C solved programs/examples on Bitwise Operators

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C program to count number of bits set to 1 in an I... >>
<< C program to find the Highest Bit Set for any give...