[英]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
错误输出
你忘记了像数组一样的位是从零开始编号的,而不是从一开始。
将您对swap
的调用swap
为:
swap(5, 4, 2, 1);
在新位中进行 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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.