c - Swapping different bits between 2 integers - C
问题描述
i need help.
I need to solve this problem of swapping 2 different bits between 2 different integers.
Examlpe (Swap bit 3 of (101) with bit 2 of (100))
Would result to (001) & (110)
My trial
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);
}
Wrong output of swap(5,4,3,2)
-> Number[1] => 5 Number => 0
解决方案
您忘记了位(如数组)是从零开始编号的,而不是从一开始的。
将您的呼叫替换为
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
推荐阅读
- vba - Visio 宏保存无宏文件
- javascript - 为什么我的 Lucky Sevens 输出不正确?
- reactjs - 我想要一个验证码来像附加图片一样做出反应
- html - 转到上一页然后返回原始页面时,Facebook Like 按钮消失
- php - elseif 当 mysql 查询没有返回任何行时
- apache-kafka - 验证分区的 Kafka 重新分配
- python - PyInstaller 无法通过 pip 安装
- regex - 使用正则表达式匹配一系列非空的分隔字符串
- html-table - 如何使用 RSelenium 将 javascript 形成的 html-table 提取到 data.frame
- linux - 在 Bash 脚本中,函数的第二个参数未按预期处理