在数字c#中插入1位

时间:2015-05-27 09:42:21

标签: c# insert numbers bits

我在插入数字时遇到问题。我有一个位置插入这1位。例如,如果我有一个数字186(代表位:1011 1010)并且我有一个位置4.它将看起来是1 011 1 1010.而我的第二个问题几乎与第一个问题相同但是操作在给定位置移除1位。如果我有位置5,则位数将为101 1010.谢谢

保持冷静并学习如何

3 个答案:

答案 0 :(得分:2)

我需要为Z80.NET project做同样的事情,以及我是如何解决的:

public static class NumberUtils
{
    public static byte WithBit(this byte number, int bitPosition, bool value)
    {
        if(bitPosition < 0 || bitPosition > 7)
            throw new InvalidOperationException("bit position must be between 0 and 7");

        if(value) 
            return (byte)(number | (1 << bitPosition));
        else 
            return (byte)(number & ~(1 << bitPosition));
    }
}

单元测试:

[Test]
public void SetBit_works_for_middle_bit()
{
    byte bit4reset = 0xFF;
    Assert.AreEqual(0xEF, bit4reset.WithBit(4, false));

    byte bit4set = 0x00;
    Assert.AreEqual(0x10, bit4set.WithBit(4, true));
}

答案 1 :(得分:1)

您可以使用System.Collections.BitArray执行此任务,它允许您将数字转换为位数组,然后处理此数字的各个位,然后将其转换回来。以下是bit在特定number position中插入 public static byte insertIntoPosition(byte number, int position, bool bit) { // converting the number to BitArray BitArray a = new BitArray (new byte[]{number}); // shifting the bits to the left of the position for (int j = a.Count - 1; j > position; j--) { a.Set (j, a.Get (j - 1)); } // setting the position bit a.Set (position, bit); // converting BitArray to byte again byte[] array = new byte[1]; a.CopyTo(array, 0); return array[0]; } 的方式:

String newStr = testStrHTML.replaceAll("\\<.*?\\>", "");

也可以通过这种方式轻松地从某个位置移除一个位。

答案 2 :(得分:0)

下面的代码将插入一个位,而不会通过for循环将其转换为位数组(将O(1)操作转换为O(N)一个)效率很低。

public static int InsertBit(int input, int pos, bool state) {
  //Split the input into two parts, one shifted and one not
  int bottom = input;
  int top = (input << 1);
  //insert a '0' or '1' before the shifted part
  if (state) top |= (1 << pos);
  else       top &= (~(1 << pos));
  //keep the top bits of top
  top &= (-1 << pos);
  //keep the bottom bits of bottom
  bottom &= ~(-1 << pos);
  //combine the two parts.
  return (bottom | top);
end;

请注意,这是https://www.topbug.net/blog/2014/11/16/how-to-insert-1-bit-into-an-integer/的翻译
所以不是我自己的代码。

删除一点甚至更容易:

public static int RemoveBit(int input, int pos) {
  //Split the input into two parts, one shifted and one not
  int bottom = input;
  int top = (input >> 1);
  //keep the top bits of x
  top &= (-1 << pos);
  //keep the bottom bits of y
  bottom &= ~(-1 << pos);
  //combine the two parts.
  return (bottom | top);
end;

请注意,删除位将保留input的符号。如果input为负,则它将1插入最高有效位。如果您不希望这样做,则必须输入unsigned int