首页 > 解决方案 > 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

标签: cbit-manipulationswap

解决方案


  1. 您忘记了位(如数组)是从零开始编号的,而不是从开始的。

    将您的呼叫替换为swap

    swap(5, 4, 2, 1);
    
  2. 在新位中进行 OR 运算的代码不会将它们移动到它们应该在新数字中进入的位位置。它们保留在源编号中被拉出的位位置。

    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
    

推荐阅读