小编典典

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

c#

我有一个函数可以将字符串转换为十六进制,

public static string ConvertToHex(string asciiString)
{
    string hex = "";
    foreach (char c in asciiString)
    {
         int tmp = c;
         hex += String.Format("{0:x2}", (uint)System.Convert.ToUInt32(tmp.ToString()));
    }
    return hex;
}

您能帮我根据我的示例函数向Binary函数写另一个字符串吗?

public static string ConvertToBin(string asciiString)
{
    string bin = "";
    foreach (char c in asciiString)
    {
        int tmp = c;
        bin += String.Format("{0:x2}", (uint)System.Convert.????(tmp.ToString()));
    }
    return bin;
}

阅读 875

收藏
2020-05-19

共1个答案

小编典典

干得好:

public static byte[] ConvertToByteArray(string str, Encoding encoding)
{
    return encoding.GetBytes(str);
}

public static String ToBinary(Byte[] data)
{
    return string.Join(" ", data.Select(byt => Convert.ToString(byt, 2).PadLeft(8, '0')));
}

// Use any sort of encoding you like. 
var binaryString = ToBinary(ConvertToByteArray("Welcome, World!", Encoding.ASCII));
2020-05-19