How to swap two bits of a byte in C

1 Answer

0 votes
#include <stdio.h>

void showBits(unsigned char ch) {
    for (int i = 1 << 8 - 1; i > 0; i = i / 2)
        (ch & i) ? printf("1") : printf("0");
}

int swap2Bits(unsigned char num, unsigned char firstPos, unsigned char secondPos) {
    unsigned int firstBit = (num >> firstPos) & 1;
    unsigned int secondBit = (num >> secondPos) & 1;
  
    unsigned int xorBit = (firstBit ^ secondBit);

    xorBit = (xorBit << firstPos) | (xorBit << secondPos);

    return num ^ xorBit;
}
   
int main()
{
    unsigned char ch = 29;
      
    showBits(ch);
  
    unsigned char result = swap2Bits(ch, 1, 2);
      
    printf("\n");
      
    showBits(result);
      
    return 0;
}
  
  
  
  
/*
run:
  
00011101
00011011
  
*/

 



answered Dec 20, 2023 by avibootz

Related questions

1 answer 83 views
83 views asked Oct 28, 2024 by avibootz
1 answer 179 views
1 answer 113 views
113 views asked May 29, 2022 by avibootz
1 answer 137 views
1 answer 70 views
70 views asked Oct 25, 2025 by avibootz
1 answer 224 views
...