简体   繁体   中英

Convert string that represent 16bits to a int c#

I am a beginner learning c#. I have coded a method that turns a two digit integer in a sequence of 16 bits

// takes input from user and convert it
private void Button_Click(object sender, RoutedEventArgs e)
    {
        string input = key.Text;
        string mykey = "";
        foreach (var item in input)
        {
            mykey += Binary(item);
        }
        key.Text = mykey;

    }


private string Binary(Char ch)
    {
        string result = string.Empty;
        int asciiCode;
        char[] bits = new char[8];

        asciiCode = (int)ch;
        result = Convert.ToString(asciiCode, 2);;
        bits = result.PadLeft(8, '0').ToCharArray();

        return string.Join("",bits);
    }

It might be a bit complicated but it is working. However my main problem is that I want to invert the process: ie from a sequence such as 0011000100110010 I should retrieve the int which is 12. Can someone help me to get on the right track?

Any help is greatly appriciated

Given the fact that you are learning C#, I will give you a simple, straightforward example even if it is not optimal or fancy. I think it would serve you purpose better.

  static int GetInt(string value)
    {
        double result = 0d;//double
        IEnumerable<char> target = value.Reverse();
        int index = 0;
        foreach (int c in target)
        {
            if (c != '0')
                result += (c - '0') * Math.Pow(2, index);
            index++;
        }

        return (int)result;
    }

This code will work with any padding. Also, you can change it to Int16 if you will or extend it as you want. Also, it assumes that the given string has the least significant bit at the end (little endian).

 var int16 = Convert.ToInt16("0011000100110010", 2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM