C Program to Check if a given Bit Position is set to One or not

«
»

This is a C Program to check if a given bit position is set to one or not.

Problem Description

This C Program checks if a given bit position is set to one or not.

Problem Solution

Take input from the user and checks bit position as shown in the program below.

advertisement
Program/Source Code

Here is source code of the C Program to check if a given bit position is set to one or not. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

/*
 * C Program to Check if a given Bit Position is set to One or not
 */
#include <stdio.h>
 
void main()
{
    unsigned int number;
    int result, position;
 
    printf("Enter the unsigned integer:\n");
    scanf("%d", &number);
    printf("enter position to be searched\n");
    scanf("%d", &position);
    result = (number >> (position));
    if (result & 1)
        printf("TRUE\n");
    else
        printf("FALSE\n");    
}
Program Explanation

In this C Program, we are reading the unsigned integer and position to be searched using ‘number’ and ‘position’ variables respectively. Compute the Binary Right Shift Operation.

advertisement

The left operand value is moved right by the number of bits specified by the right operand. If else condition statement is used to copy a bit to the result if it exists in both operands using Binary AND operator. Print the bit position which is set to one or not.

Runtime Test Cases
 
$ cc bit14.c
$ a.out
Enter the unsigned integer:
128
enter position to be searched
7
TRUE

Sanfoundry Global Education & Learning Series – 1000 C Programs.

advertisement

Here’s the list of Best Reference Books in C Programming, Data-Structures and Algorithms

If you wish to look at programming examples on all topics, go to C Programming Examples.

advertisement
advertisement
advertisement
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn