Q:

How to check if a particular bit is set in C?

0

How to check if a particular bit is set in C?

All Answers

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

To check the nth bit, shift the ‘1’ nth position toward the left and then “AND” it with the number.

An algorithm to check the bits

 Bit = Number & (1 << nth)

A simple program to check a bit:

 

#include <stdio.h>
int main(int argc, char *argv[])
{
    unsigned char cData=0xFc;
    int iPos =0;
    printf("Initially cData = 0x%x\n\n",cData);
    printf("Enter the position which you want check = ");
    scanf("%d",&iPos);
    if(cData & (1<<iPos))   //Check bit set or not
    {
        printf("\n\nBit is One\n");
    }
    else
    {
        printf("\n\nBit is zero\n");
    }
    return 0;
}

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

total answers (1)

How to toggle a particular bit in C?... >>
<< How to clear a particular bit in C?...