1

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

2 Answers 2

1
  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
    
3
  • Hello @Govind Parmar, excuse me but that results into Number[1] => 1 Number[2] => 4 not the required result. Sep 7, 2018 at 2:42
  • 1
    @HassanA.El-Seoudy You're right; I just updated my answer Sep 7, 2018 at 2:43
  • @HassanA.El-Seoudy No problem, if you are satisfied with my answer feel free to accept it by clicking the check mark! Sep 7, 2018 at 2:53
0
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);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.