C#中的字符串到二进制

Nan*_* HE 23 c# string binary types

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

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;
}
Run Code Online (Sandbox Code Playgroud)

你能帮我把另一个字符串写成基于我的样本函数的二进制函数吗?

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;
}
Run Code Online (Sandbox Code Playgroud)

Jaa*_*jan 39

干得好:

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));
Run Code Online (Sandbox Code Playgroud)

  • 他的例子说asciiString作为参数.我也不知道二进制数组应该是什么格式.但您可以根据需要更改编码. (8认同)
  • 请使用`System.Text.UTF8Encoding`. (5认同)

ser*_*0ne 10

听起来你基本上想要一个ASCII字符串,或者更好的是,一个byte [](因为你可以使用你喜欢的编码模式将字符串编码为byte [])成为一串零和一串?即10101001001010010010010100101001010010101010101010010010111101101010

这将为你做到这一点......

//Formats a byte[] into a binary string (010010010010100101010)
public string Format(byte[] data)
{
    //storage for the resulting string
    string result = string.Empty;
    //iterate through the byte[]
    foreach(byte value in data)
    {
        //storage for the individual byte
        string binarybyte = Convert.ToString(value, 2);
        //if the binarybyte is not 8 characters long, its not a proper result
        while(binarybyte.Length < 8)
        {
            //prepend the value with a 0
            binarybyte = "0" + binarybyte;
        }
        //append the binarybyte to the result
        result += binarybyte;
    }
    //return the result
    return result;
}
Run Code Online (Sandbox Code Playgroud)