Binary NOT in c#

Keeponfalling 41 Reputation points
2020-12-01T21:47:53.403+00:00

Hello
I have a misunderstanding issue...if you can please help me.
I get a binary number: 110 for example, in string format and I want to apply the not ~ operator and get 001.

I try to convert it to sbyte or byte but for "1" I get 49. Also, I convert it to int and apply the ~ and get a different result, not what I looking for and I don't understand why.
Can you give me some suggestions, please. Thanks.

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,480 questions
{count} votes

Accepted answer
  1. Andrea Angella 171 Reputation points MVP
    2020-12-01T22:51:20.493+00:00

    The Convert class can help you to convert binary numbers between the string and integer types.

    Convert.ToInt32(input, 2) helps you to take your binary number as a string and convert it into an integer
    Convert.ToString(n, 2) helps you to convert an integer into its binary representation as a string

    The tricky part is that ToString prints all the binary digits in the number (32 bits) so if you only want to consider 3 digits you need to only take the last 3 from the string generated.

    string BinaryNot(string input)           // 110  
    {                                           
        var n = Convert.ToInt32(input, 2);   // 6  
        var notN = Convert.ToString(~n, 2);  // 11111111111111111111111111111001  
        return notN[^input.Length..];        // 001  
    }  
    

    In this case, however, using a simple string manipulation and invert 0s with 1s is easier and more compact.

    string BinaryNot(string input) => string.Concat(input.Select(x => x == '0' ? '1' : '0'));  
    
    1 person found this answer helpful.
    0 comments No comments

6 additional answers

Sort by: Most helpful
  1. WayneAKing 4,921 Reputation points
    2020-12-02T04:33:14.797+00:00

    In my example, I separated the steps into three operations to facilitate
    reading the code and observing what happens at each step of the conversion.
    If you want compact code you can concatenate the steps into a single line:

    string str1 = "11001110011";
    string str2 = "";
    for (int n = 0; n < str1.Length; ++n)
    {
        str2 += (~(str1[n] - '0')) & 0x01;
    }
    
    Console.WriteLine(" Input: {0}\nOutput: {1}", str1, str2);
    

    Input: 11001110011
    Output: 00110001100

    • Wayne
    0 comments No comments

  2. Keeponfalling 41 Reputation points
    2020-12-02T07:38:41.827+00:00

    Thank you all for your help..now make sense. So sorry that I can't accept all answers.
    The great community ever for my c# problems :)
    Thank's again.

    0 comments No comments