在 C# 中将带有二进制的字符串转换为二进制

turning a string with binary into binary in C#

假设我有一个包含二进制的字符串,如下所示:

string test = "01001010";

所以我想做这样的事情:

someFunc(test);

并且此函数将 return 与测试变量完全相同,但以字节形式而不是字符串形式。

示例:

using System;

class Program
{
    static void Main()
    {
        Console.WriteLine(Convert.ToChar(someFunc(Console.ReadLine())));
    }
}

此程序提示您使用 Console.ReadLine 输入一个字节(return 是一个字符串),将其转换为字节,然后将其转换为字符。

我该怎么做?

已编辑:

取char后取char,与结果字节相加乘以2,二进制转十进制(除最后一个char外,应直接相加)

然后 return byte as char.

public static char someFunc(string bs) { 
    byte result = 0;
    for (int i = 0; i < bs.Length - 1; i++)
    {
        if (bs[i].Equals('1')) 
        {
            result += 1;
        }
        result *= 2;
    }
    if (bs[bs.Length - 1].Equals('1')) 
    {
        result++;
    }
    return (char) result;
}

returns J 代表“01001010”

您好,这是我在 java 中使用的一种实现,但这也适用于 C#。我是你需要一些语法更改。

static int someFunc(String s){
    int binary = 0x00;
    for(int i=0;i<8;i++){
        if(s.charAt(i) == '1')
            binary =(binary<<1) | 0x01;
        else if(s.charAt(i) == '0')
            binary =(binary<<1) | 0x00;

    }
    return binary;
}

你可以这样写:

using System;

    class Program
    {
        static byte someFunc(string text)
        {
                byte t = 0;
                for (int i = 0; i < 8; i++)
                         t = (byte)(t * 2 + (text[i] - '0'));
                return t;
        }
        static void Main()
        {
            Console.WriteLine(Convert.ToChar(someFunc(Console.ReadLine())));
        }
    }

但在使用 someFunc() 之前检查字符串是否正常(例如,如果输入为“10102010”,则会显示错误消息)

使用Convert.ToInt32(string, int) where string is the string you want to convert, and int is the base of the number system you want to convert from, in your case base 2 or binary. Or if you really desperately need it to be a byte, then you can use Convert.ToByte(string, int)。像这样:

using System;

class Program
{
    public static void Main()
    {
        var input = Console.ReadLine(); // 01001010
        var number = Convert.ToInt32(input, 2);
        Console.WriteLine(number); // prints '74'
    }
}

请注意,如果给定的输入字符串包含对给定基数而言非法的字符,Convert.ToXyz() 将抛出类型为 FormatException 的异常。对于基数为 2 的任何不是 01 的字符,您可能想要捕获此类异常,或者检查输入字符串中的所有字符是否为“0”或“1”事先