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

Swapping different bits between 2 integers - C

我需要帮助。

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

示例(将 (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

  1. 您忘记了位,就像数组一样,是从 0 开始编号的,而不是 one

    将您对 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
    
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);
}