c#中的字符串到二进制
本文关键字:二进制 字符串 | 更新日期: 2023-09-27 17:50:05
我有一个将字符串转换为十六进制的函数,如下所示,
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;
}
你能帮我在我的示例函数的基础上再写一个字符串到二进制函数吗?
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;
}
给你:
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));
听起来你基本上想要一个ASCII字符串,或者更理想的是一个字节[](因为你可以用你喜欢的编码模式将你的字符串编码为字节[])变成一个1和0的字符串?即101010010010100100100101001010010100101001010010101000010111101101010
这将为您做…
//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;
}
这是一个扩展函数:
public static string ToBinary(this string data, bool formatBits = false)
{
char[] buffer = new char[(((data.Length * 8) + (formatBits ? (data.Length - 1) : 0)))];
int index = 0;
for (int i = 0; i < data.Length; i++)
{
string binary = Convert.ToString(data[i], 2).PadLeft(8, '0');
for (int j = 0; j < 8; j++)
{
buffer[index] = binary[j];
index++;
}
if (formatBits && i < (data.Length - 1))
{
buffer[index] = ' ';
index++;
}
}
return new string(buffer);
}
你可以这样使用:
Console.WriteLine("Testing".ToBinary());
,如果您添加'true'作为参数,它将自动分隔每个二进制序列。
下面将为您提供每个字符的低字节的十六进制编码,这看起来像您所要求的:
StringBuilder sb = new StringBuilder();
foreach (char c in asciiString)
{
uint i = (uint)c;
sb.AppendFormat("{0:X2}", (i & 0xff));
}
return sb.ToString();