Q:

How to toggle a particular bit in C?

0

How to toggle a particular bit in C?

All Answers

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

Bitwise XOR (^) operator use to toggle the bit of an integral data type. To toggle the nth bit shift the ‘1’ nth position toward the left and “XOR” it.

An algorithm to toggle the bits

Number  ^=  (1<< nth Position)

A simple program to toggle a bit:

 

#include <stdio.h>
int main(int argc, char *argv[])
{
    unsigned char cData=0xF8;
    int iPos =0;
    printf("Initially cData = 0x%x\n\n",cData);
    printf("Enter the position which you want toggle = ");
    scanf("%d",&iPos);
    //toggle the nth bit.
    cData ^= 1<<iPos;
    //Print the data
    printf("\n\n%dth Bit Set Now cData will be = 0x%x\n",iPos,cData);
    return 0;
}

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

total answers (1)

Write an Efficient C Program to Reverse Bits of a ... >>
<< How to check if a particular bit is set in C?...