简体   繁体   中英

Swapping different bits between 2 integers - C

i need help.

I need to solve this problem of swapping 2 different bits between 2 different integers.

Examlpe (Swap bit 3 of (101) with bit 2 of (100))

Would result to (001) & (110)

My trial

void swap(unsigned int numberA, unsigned int numberB, int bitPositionA, int bitPositionB)
{
    unsigned int aShift = 1 << bitPositionA, bShift = 1 << bitPositionB;
    unsigned int bitA = numberA & aShift;
    unsigned int bitB = numberB & bShift;


    numberB &= ~bShift; // Set the bit to `0`
    numberB |= bitA;    // Set to the actual bit value

    numberA &= ~aShift; // Set the bit to `0`
    numberA |= bitB;    // Set to the actual bit value

    printf("Number[1] => %d Number => %d",numberA,numberB);
}

Wrong output of swap(5,4,3,2) -> Number[1] => 5 Number => 0

  1. You're forgetting that bits, like arrays, are numbered starting from zero , not one .

    Replace your call to swap with:

     swap(5, 4, 2, 1);
  2. The code that ORs in the new bits does not move them into the bit location that they're supposed to go into in the new number. They remain at the bit location that they were pulled out of in the source number.

     numberB &= ~bShift; // Set the bit to `0` if(bitA) bitA = 1 << bitPositionB; numberB |= bitA; // Set to the actual bit value numberA &= ~aShift; // Set the bit to `0` if(bitB) bitB = 1 << bitPositionA; numberA |= bitB; // Set to the actual bit value
void swap(unsigned int numberA, unsigned int numberB, int bitPositionA, int bitPositionB)
{
    unsigned int aShift = 1 << bitPositionA-1, bShift = 1 << bitPositionB-1;
    unsigned int bitA = numberA & aShift;
    unsigned int bitB = numberB & bShift;


    numberB &= ~bShift; // Set the bit to `0`
    numberB |= bitA >> (bitPositionB-1);    // Set to the actual bit value

    numberA &= ~aShift; // Set the bit to `0`
    numberA |= bitB >> (bitPositionA-1);    // Set to the actual bit value

    printf("Number[1] => %02X Number => %02X \n",numberA,numberB);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM