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,885 questions

51,811 answers

573 users

How to define macros to get bit, set bit, clear bit and flip bit in C

1 Answer

0 votes
#include <stdio.h>

#define GetBit(num, bit) ((num & (1 << bit)) != 0) 
#define SetBit(num, bit) (num |= (1 << bit))
#define FlipBit(num, bit) (num ^= (1 << bit))
#define ClearBit(num, bit) (num &= ~(1 << bit))

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");
    }
}

int main() {
    unsigned int num = 0;
    
    SetBit(num, 3);
    print_bits(num, 8);
    
    printf("\n");
    (GetBit(num, 5)) ? printf("1") : printf("0");
    
    printf("\n");
    (GetBit(num, 3)) ? printf("1") : printf("0");
    
    FlipBit(num, 5);
    printf("\n");
    print_bits(num, 8);
    
    ClearBit(num, 3);
    printf("\n");
    print_bits(num, 8);
    
    return 0;
}
 
 
 
 
/*
run:
 
00001000
0
1
00101000
00100000
 
*/

 



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

Related questions

1 answer 95 views
95 views asked Sep 30, 2023 by avibootz
1 answer 213 views
213 views asked Aug 28, 2016 by avibootz
2 answers 220 views
220 views asked Jan 5, 2016 by avibootz
2 answers 153 views
1 answer 158 views
...