简体   繁体   English

在 2 个整数之间交换不同的位 - 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.我需要解决在 2 个不同整数之间交换 2 个不同位的问题。

Examlpe (Swap bit 3 of (101) with bit 2 of (100))示例(将 (101) 的第3位与 (100) 的第2位交换)

Would result to (001) & (110)将导致(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(5,4,3,2) -> Number[1] => 5 Number => 0错误输出

  1. You're forgetting that bits, like arrays, are numbered starting from zero , not one .你忘记了像数组一样的位是从零开始编号的,而不是从一开始

    Replace your call to swap with:将您对swap的调用swap为:

     swap(5, 4, 2, 1);
  2. The code that ORs in the new bits does not move them into the bit location that they're supposed to go into in the new number.在新位中进行 OR 运算的代码不会将它们移动到它们应该在新数字中进入的位位置。 They remain at the bit location that they were pulled out of in the source number.它们保留在它们在源编号中被拉出的位位置。

     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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM