How to toggle particular bit in given number - C program

There are many ways & everyone has different thinking to do the same. I would like to demonstrate my way to do the same. For the same first you need to have the clear understanding of bit-wise operation in C. You need to know what is "bit wise AND" & what is "logical AND" operation.
  • && Means Logical AND
  • & means Bitwise AND
Program:
______________________________
#include <stdio.h>
#define MSB (1 << ((sizeof(int)*8)-1))
#define BITPOS(pos) (1 << pos)
#define MAXVAL (MSB | (MSB-1))
int toggleBit(int num, char pos)
{
int temp = (num & (BITPOS(pos)));
temp = ~temp;
//printf("%x\n%x\n",temp, MAXVAL); //To debug the code
if(temp != MAXVAL)
{
num = num & temp;
}
else
{
temp = (temp & (BITPOS(pos)));
num = num | temp;
}
//printf("%x\n",num); //To debug the code
return num;
}
int main() {
int ProgBits = 0xFF08; //Number with Programmable Bits
char bitposition = 2;
printf("Given number: %x\n",ProgBits);
ProgBits = toggleBit(ProgBits, bitposition); //Toggle particular bit in a given number
printf("Number with toggle bit position %d: %x\n",bitposition, ProgBits);
return 0;
}                                                                                                                                                                                                                                                                                                                                                           Output:                                                                                                                                                             Given number: ff08
Number with toggle bit position 2: ff0c

Share on Google Plus

About Kapil Thakar

"I am Kapil Thakar, an Embedded Engineer cum Blogger wants to learn new things. I love to share my knowledge solutions to the problems. Interested in Blogging, Creative-Writing, SEO, Website Creation, Video Making, Editing, Affiliation Programs, Online Making Money."
    Blogger Comment
    Facebook Comment

0 comments :

Post a Comment

Related Posts Plugin for WordPress, Blogger...