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 a single bit in C

1 Answer

0 votes
#include <stdio.h>
 
void print_bits(unsigned int num, unsigned int size) {
    for (int i = 1 << (size - 1); i > 0; i = i / 2) {
        (num & i) ? printf("1") : printf("0");
    }
}
 
unsigned int toggle_bit(unsigned int number, unsigned int bit_number) {
    return number ^ ((unsigned int )1 << bit_number);
}
 
int main() {
    unsigned int num = 157;
     
    print_bits(num, 8);
     
    num = toggle_bit(num, 1);
     
    printf("\n");
     
    print_bits(num, 8);
 
    return 0;
}
 
 
 
/*
run:
 
10011101
10011111
 
*/

 



answered Sep 30, 2023 by avibootz

Related questions

1 answer 174 views
1 answer 93 views
93 views asked Sep 30, 2023 by avibootz
1 answer 96 views
96 views asked Sep 30, 2023 by avibootz
1 answer 91 views
91 views asked Sep 29, 2023 by avibootz
1 answer 105 views
2 answers 143 views
143 views asked May 9, 2022 by avibootz
...