[英]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.