我需要帮助。
我需要解决在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
swap
的电话改为:
swap(5, 4, 2, 1);
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);
}