如何转换一串位,例如
0100100001100101011011000110110001101111001000000101011101101111011100100110110001100100
转换成一串 ASCII 字符,例如:“Hello World”?
如何转换一串位,例如
0100100001100101011011000110110001101111001000000101011101101111011100100110110001100100
转换成一串 ASCII 字符,例如:“Hello World”?
您需要将它们分成 8 个字符的字符串(字节),调用Convert.ToByte(str, 2)
,将它们放入 a 中byte[]
,然后调用Encoding.ASCII.GetString()
。
这个代码示例应该很清楚:
String bits = "01001001000......0001100100"; // shortened here for demo purposes
byte[] bArr = new byte[bits.Length / 8];
for (int i = 0; i < bits.Length / 8; i++)
{
String part = bits.Substring(i * 8, 8);
bArr[i] += Convert.ToByte(part, 2);
}
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
Console.WriteLine(encoding.GetString(bArr));
基本上将字符串分成偶数部分,将结果字节存储在字节数组中,然后以特定的编码对其进行解析。
public string GetBytesFromBinaryString(String binary)
{
var list = new List<Byte>();
for (int i = 0; i < binary.Length; i += 8)
{
String t = binary.Substring(i, 8);
list.Add(Convert.ToByte(t, 2));
}
return Encoding.ASCII.GetString(list.ToArray());
}
测试:
var data = GetBytesFromBinaryString("0100100001100101011011000110110001101111001000000101011101101111011100100110110001100100");
输出:
“你好世界”
使用此方法
private byte[] GetAsByteArray(string BinaryString)
{
return Enumerable.Range(0, BinaryString.Length / 8)
.Select(i => Convert.ToByte(BinaryString.Substring(i * 8, 8), 2)).ToArray();
}
然后像这样称呼它
string binaryString = "0100100001100101011011000110110001101111001000000101011101101111011100100110110001100100";
string convertedText = System.Text.Encoding.ASCII.GetString(GetAsByteArray(binaryString));