0

我是学习c#的初学者。我编写了一种方法,可以将两位整数转换为 16 位序列

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

它可能有点复杂,但它正在工作。但是我的主要问题是我想反转这个过程:即从 0011000100110010 之类的序列中,我应该检索 12 的 int。有人可以帮助我走上正确的轨道吗?

非常感谢任何帮助

4

2 回答 2

1

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).

于 2013-11-02T08:38:03.623 回答
0
 var int16 = Convert.ToInt16("0011000100110010", 2);
于 2013-11-02T07:29:06.370 回答