二元系统中的否定和递增值

时间:2013-09-23 11:40:47

标签: c# visual-studio-2012 binary increment negate

我有二进制数,我需要:

1)否定所有字节

2)加1以否定数字

所以,我写了这个:

public string u2_number_plus = "1001";
public string u2_number_minus = "";

public string binToU2()
        {
            int length = u2_number_plus.Length;
            int temp = 1;

            //negate all bytes
            for (int a = 0; a < length; a++)
            {
                if (u2_number_plus[a] == '1')
                    u2_number_minus += '0';
                else
                    u2_number_minus += '1';
            }

            //add 1 to my new (because negate) number
            for (int b = length - 1; b >= 0; b--)
            {
                if (u2_number_minus[b] == 0 && temp == 1)
                {
                    u2_number_minus = u2_number_minus.Replace(u2_number_minus[b], '1');
                    temp = 0;
                }
                else if (u2_number_minus[b] == 1 && temp == 1)
                {
                    u2_number_minus = u2_number_minus.Replace(u2_number_minus[b], '0');
                    temp = 1;
                }
                else
                    break;
            }

            return u2_number_minus;
        }

我的函数binToU2()返回negate但不返回增量值。 如果输入数据是1001我应该得到0111,但函数只返回0110.我在哪里犯了错误?

2 个答案:

答案 0 :(得分:1)

当你检查u2_number_minus [b]时,你需要将它与'0'和'1'进行比较,而不是数字0和1。

if (u2_number_minus[b] == '0' && temp == 1)

还有另一个错误,在字符串中使用Replace更改所有出现的指定字符,但我们只想更改指定位置的那个。 C#没有replaceAt,但可以创建一个辅助函数来执行此操作。见Replacing a char at a given index in string?。我在这里使用了Jon Skeet的代码:

public static class ReplaceHelper
{
public static string ReplaceAt(this string input, int index, char newChar)
  {
    if (input == null)
    {
      throw new ArgumentNullException("input");
    }
    char[] chars = input.ToCharArray();
    chars[index] = newChar;
    return new string(chars);
  }
}

并更改替换行以使用ReplaceAt,例如

u2_number_minus = u2_number_minus.ReplaceAt(b, '1');

答案 1 :(得分:-1)

没有真正得到你想要做的或你需要的地方,但无论如何,也许你想使用BitArray而不是挣扎于字符串操作。

BitArray实际上是存储位,并为您提供了否定数组或使用其他操作的基本功能......

我举个例子:

        // define a bit array with length=4 and false as default value for each bit.
        var bits = new BitArray(4, false);

        bits.Not(); // negate --> all 4 bits are now true.

        // your example:
        bits = new BitArray(new bool[] { true, false, false, true });
        // to inverst/negate it
        bits.Not();

        // convert to string:
        string bitString = string.Empty;
        foreach (var bit in bits)
        {
            bitString += (bool)bit ? "1" : "0";
        }

        Console.WriteLine(bitString);

        // from string:
        string longBitString = "01000101001001010100010010010";
        var longIntArray = longBitString.ToCharArray().Select(p => p.Equals('0') ? false : true).ToArray();
        var longBitArray = new BitArray(longIntArray);