在2个整数之间交换不同的位-C

时间:2018-09-07 02:10:30

标签: c bit-manipulation swap

我需要帮助。

我需要解决在2个不同的整数之间交换2个不同的位的问题。

Examlpe(将(101)的 3 位与(100)的 2 位交换)

结果将为(001)(110)

我的审判

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);
}

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

的输出错误

2 个答案:

答案 0 :(得分:1)

  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
    

答案 1 :(得分: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);
}
相关问题