你非常接近;
public static int setNibble(int num, int nibble, int which)
{
int output;
if(which ==0)
{
output = (num & /*65280*/ 0xFFFFFFF0 ) | nibble;
}
else
{
int shiftNibble = nibble << (4*which) ;
int shiftMask = 0x0000000F << (4*which) ;
output = (num & ~shiftMask) | shiftNibble ;
}
return output;
}
实际上,您可以以which == 0
单独处理大小写为代价来简化代码。事实上,你是在if
用一个换班和一个not
。根本没有太大区别,代码更清晰,更优雅。
public static int setNibble(int num, int nibble, int which) {
int shiftNibble= nibble << (4*which) ;
int shiftMask= 0x0000000F << (4*which) ;
return ( num & ~shiftMask ) | shiftNibble ;
}
掩码的想法是完全清除半字节将在结果中占据的相同 4 个位置。否则,该位置将在半字节为零的那些位中包含垃圾。例如
// Nibble 77776666555544443333222211110000
num= 0b01001010111101010100110101101010 ;
nibble= 0b0010 ; // 2
which= 3 ;
shiftNibble= 0b00000000000000000010000000000000 ;
shiftMask= 0b00000000000000001111000000000000 ;
num= 0b01001010111101010100110101101010 ;
~shiftMask= 0b11111111111111110000111111111111 ;
num & ~shiftMask= 0b01001010111101010000110101101010 ;
// ~~~~ Cleared!
( num & ~shiftMask )
| nibble 0b01001010111101010010110101101010 ;
// ~~~~ Fully set; no garbage!