For example, I have a uint with some bits set to 1:
uint x = 0b0000_0100_0010_0000
I need to repeat the bits to the left/right N times. Like this:
Repeat left, N = 1: 0000_1100_0110_0000
Repeat left, N = 2: 0001_1100_1110_0000
Repeat right, N = 4: 0000_0111_1111_1110
So it's like "bitwise shift with repeat". Is there an effective way to achieve this, preferably without looping?
You can achieve this with a recursive function, using a shift operation with a bitwise or:
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);
}
}
Usage
uint input = 0b0000_0100_0010_0000;
uint shiftLeft1 = RepeatBits(input, 1, true);
uint shiftLeft2 = RepeatBits(input, 2, true);
uint shiftRight3 = RepeatBits(input, 3, false);
Output
0000_1100_0110_0000
0001_1100_1110_0000
0000_0111_1011_1100