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

51,892 answers

573 users

How to swap two bits of a 32-bit integer number in C

1 Answer

0 votes
#include <stdio.h>
 
void print_bits(unsigned int n, int size) {
    for (unsigned int i = 1 << (size - 1); i > 0; i = i / 2) {
        (n & i) ? printf("1") : printf("0");
    }
}

int swap_bits(int num, int pos1, int pos2) {
    if (( (num & (1 << pos1)) >> pos1) ^ ( (num & (1 << pos2)) >> pos2)) {
        num ^= (1 << pos1);
        num ^= (1 << pos2);
    }
    
    return num;
}
  
int main()
{
    unsigned int number = 41337; // // 0000000000000000101000010-1-111-0-01
    int pos1 = 2;
    int pos2 = 6;
      
    print_bits(number, 32);
    printf("\n");
     
    unsigned int swaped_bits = swap_bits(number, pos1, pos2);
     
    print_bits(swaped_bits, 32);
 
    return 0;
}
  
  
  
    
/*
run:
    
00000000000000001010000101111001
00000000000000001010000100111101
    
*/

 



answered Dec 22, 2023 by avibootz
edited Dec 22, 2023 by avibootz

Related questions

1 answer 112 views
1 answer 129 views
1 answer 133 views
1 answer 127 views
1 answer 108 views
1 answer 91 views
...