如何将2位从一个int复制到另一个?

bra*_*ter 5 c c++ bit-manipulation

我有两个无符号的int数:ab(b是无符号的int指针).我想将第8位和第9位复制a到第2位和第3位b(所有索引都是0).

这就是我这样做的方式:

 bool secondBit =  (a & (1 << 8) ) ;
 bool thirdBit =   (a & (1 << 9) ) ;

 if (secondBit) {
     *b |= (1u << 2);
 }
 if (thirdBit) {
     *b |= (1u << 3);
Run Code Online (Sandbox Code Playgroud)

提醒:b是一个无符号的int指针.

有没有更好的方法呢?

Mic*_*ael 13

清除相关位*b并将它们设置为您想要的位a:

*b = (*b & ~0xC) | ((a & 0x300) >> 6);

// This is the 'not' of 00001100, in other words, 11110011
~0xC;

// This zeros the bits of *b that you do not want (b being a pointer)
*b & ~0xC;   // *b & 11110011

//This clears all of a except the bits that you want
a & 0x300;

// Shift the result into the location that you want to set in *b (bits 2 and 3)   
((a & 0x300) >> 6);

// Now set the bits into *b without changing any other bits in *b
*b = (*b & ~0xC) | ((a & 0x300) >> 6);
Run Code Online (Sandbox Code Playgroud)