toggle bit

how can I toggle all the bits of any given number using a shortest C code

Invert it. See Wikipedia on Bitwise operation and your courses learning material.

The direct answer to your question :

int main() {
unsigned short int v = 7;                             // First 13  MSB == 0; Last 3 LSB == 1 --> 0000000000000111
unsigned short int toggled_bit = (0xffff ^ v) ; // toggled_bit now have a bits pattern  --> 1111111111111000

   printf("Actual Variable == %u --- toggled bit value %u\n", v, toggled_bit);
}

The shortest answer, isn;t it?

Now a bigger code; write a function :wink:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/errno.h>

unsigned short toggleBits ( unsigned short a_val) {
   return (0xffff ^ a_val);
};

int main(int argc, **argv) {
unsigned short int val = 0;
   if(argc < 2) exit(1);
   val = (unsigned short) atoi(argv[1]);
   printf(" val == %u\n" , val);
   for(int i = 0; i < 4; i++) {
      val = toggleBits(val);
      printf(" val == %u\n" , val);
   } 
   return 0;
}

However, if you wana just toggle a single bit (say n'th bit) , then instead of FFFF, use a value equivalent to 2^n (2 to the power n) and do the XOR operation exactly similar to the above code.

Let me know, if you need any specific question. You still need to explore yourself a lot by writing simple codes doing such bitwise operation to get more clarity.

1 Like

Ha, I can do shorter:

unsigned short int v = 7;
unsigned short int toggled_bit = ~v;
1 Like

:cool: Ya the shortest one!!!!

that solves the query