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

问题描述 投票:1回答:2

我需要帮助。

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

示例(交换(101)的第3位,第2位为(100))

会导致(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

c bit-manipulation swap
2个回答
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

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);
}
© www.soinside.com 2019 - 2024. All rights reserved.