Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,890 questions

51,817 answers

573 users

How to toggle (invert) the Nth bit of a number in C

1 Answer

0 votes
#include <stdio.h>
  
void print_bits(unsigned int n) { 
    for (int i = 31; i >= 0; i--)
       printf("%d", (n >> i) & 1);
    printf("\n");
}
  
int main()
{
    int num = 15, N = 2;
 
    print_bits(num);
    print_bits(1 << N);
     
    num = num ^ (1 << N);
    print_bits(num);
    printf("%d\n", num);
	
	N = 7;
	num = num ^ (1 << N);
	print_bits(num);
	
    return 0;
}
  
  
  
/*
run:
  
00000000000000000000000000001111
00000000000000000000000000000100
00000000000000000000000000001011
11
00000000000000000000000010001011
  
*/

 



answered Jul 5, 2020 by avibootz

Related questions

1 answer 105 views
105 views asked Sep 30, 2023 by avibootz
1 answer 156 views
156 views asked Jul 5, 2020 by avibootz
1 answer 198 views
198 views asked Jul 5, 2020 by avibootz
1 answer 115 views
1 answer 146 views
1 answer 137 views
1 answer 76 views
...