简体   繁体   English

将代表16位的字符串转换为int C#

[英]Convert string that represent 16bits to a int c#

I am a beginner learning c#. 我是初学者,学习C#。 I have coded a method that turns a two digit integer in a sequence of 16 bits 我已经编码了一种方法,该方法可以按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);
    }

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? 但是,我的主要问题是我想反转该过程:即,从诸如0011000100110010之类的序列中,我应该检索一个12的整数。有人可以帮助我走上正确的道路吗?

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. 考虑到您正在学习C#的事实,即使它不是最佳的或花哨的,我也会给您提供一个简单直接的示例。 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. 另外,您可以根据需要将其更改为Int16或扩展它。 Also, it assumes that the given string has the least significant bit at the end (little endian). 同样,它假定给定的字符串的末尾最低有效位(小尾数)。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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