Search code examples
c#visual-studio-2012binaryincrementnegate

Negate and increment value in binary system


I've got binary number and I need to:

1) negate all bytes

2) add 1 to negate number

So, I wrote this:

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;
        }

My function binToU2() returns negate but not increment value. If input data is 1001 I should get 0111, but function returns just 0110. Where I made a mistake?


Solution

  • When you are doing the checking of u2_number_minus[b] you need to compare it against '0' and '1' not the number 0 and 1.

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

    There is also another error, the use of Replace changes all occurrences of the specified character in the string, but we only want to change the one at the specified position. C# does not have replaceAt, but a helper function can be created to do this. See Replacing a char at a given index in string?. I used Jon Skeet's code here:

    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);
      }
    }
    

    and change the Replace lines to use ReplaceAt eg

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