【问题标题】:What is an effective way of repeating bits in C#? [closed]在 C# 中重复位的有效方法是什么? [关闭]
【发布时间】:2020-08-16 04:23:11
【问题描述】:

例如,我有一个 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

所以这就像“重复按位移位”。有没有一种有效的方法来实现这一点,最好不要循环?

【问题讨论】:

  • 不能开箱即用。
  • @TanveerBadar 如果不循环就无法实现,也许有办法只用一点点?
  • “左移,然后按位或”可以看作是一个乘法,所以x * ((2 << N) - 1) 可以做到只要移位的位不与现有位重叠

标签: c# bitwise-operators bit bit-shift


【解决方案1】:

您可以通过递归函数来实现这一点,使用带按位或的移位操作:

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

【讨论】:

  • 希望编译器能够识别尾递归并再次将其转换为循环。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-12
  • 1970-01-01
  • 2017-09-15
  • 2016-07-14
相关资源
最近更新 更多