问题描述
例如,我有一个uint,并将某些位设置为1:
uint x = 0b0000_0100_0010_0000
我需要左右重复N次。像这样:
重复向左,N = 1:0000_1100_0110_0000
重复向左,N = 2:0001_1100_1110_0000
重复向右,N = 4:0000_0111_1111_1110
因此,这就像“按位移位并重复”。有没有一种有效的方法来实现这一目标,最好不要循环?
解决方法
您可以使用递归函数(通过按位或)进行移位操作来实现此目的:
static uint RepeatBits(uint input,int times,bool left)
{
if (times == 0)
{
return input;
}
else
{
return (left ? (input << times) : (input >> times)) | RepeatBits(input,times - 1,left);
}
}
用法
uint input = 0b0000_0100_0010_0000;
uint shiftLeft1 = RepeatBits(input,1,true);
uint shiftLeft2 = RepeatBits(input,2,true);
uint shiftRight3 = RepeatBits(input,3,false);
输出
0000_1100_0110_0000
0001_1100_1110_0000
0000_0111_1011_1100