Tom*_*ult 4 c bit-manipulation bit bitwise-operators
我刚试过这段代码:
void swapBit(unsigned char* numbA, unsigned char* numbB, short bitPosition)//bitPosition 0-x
{
unsigned char oneShift = 1 << bitPosition;
unsigned char bitA = *numbA & oneShift;
unsigned char bitB = *numbB & oneShift;
if (bitA)
*numbB |= bitA;
else
*numbB &= (~bitA ^ oneShift);
if (bitB)
*numbA |= bitB;
else
*numbA &= (~bitB ^ oneShift);
}
Run Code Online (Sandbox Code Playgroud)
交换a和b的位位置x,但由于if()我认为有更好的东西.
当我看到这个:
*numbB &= (~bitA ^ oneShift);
Run Code Online (Sandbox Code Playgroud)
我真的认为有一种更简单的方法.如果你有东西给我,我会接受它:)
提前致谢
首先,您应该在数字中设置相应的位置0,然后将其与实际位进行或运算,删除所有条件:
*numbB &= ~oneShift; // Set the bit to `0`
*numbB |= bitA; // Set to the actual bit value
Run Code Online (Sandbox Code Playgroud)
其他数字相同.