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 set 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 set_bit(unsigned int number, unsigned int bit_number) {
    return number | ((unsigned int)1 << bit_number);
}
 
 
int main() {
    unsigned int num = 136;
     
    print_bits(num, 8);
     
    num = set_bit(num, 5);
     
    printf("\n");
     
    print_bits(num, 8);
 
    return 0;
}
 
 
 
/*
run:
 
10001000
10101000
 
*/

 



answered Sep 29, 2023 by avibootz
edited Sep 30, 2023 by avibootz

Related questions

1 answer 93 views
93 views asked Sep 30, 2023 by avibootz
1 answer 105 views
105 views asked Sep 30, 2023 by avibootz
1 answer 96 views
96 views asked Sep 30, 2023 by avibootz
1 answer 102 views
1 answer 83 views
1 answer 115 views
...