问题是将非ASCII字符转换为二进制字符,反之亦然
string of bits to string of char
string result = "";
while (value.Length > 0)
{ var first8 = value.Substring(0, 8);
value = value.Substring(8);
var number = Convert.ToInt64(first8, 2);
result += (char)number;
和 字符字符串到位字符串
string S = "";
byte[] asciiBytes = Encoding.ASCII.GetBytes(value);
for (int i = 0; i < asciiBytes.Length; i++)
for (int j = 0; j < 8; j++)
{
S += (asciiBytes[i] & 0x80) > 0 ? "1" : "0";
asciiBytes[i] <<= 1;
}
return S;
如果我的代码最好,您可以更正吗?
答案 0 :(得分:0)
您可以将字符串拆分为8个字符串,使用Convert.ToByte将其转换为字节,然后使用Encoding.ASCII.GetString将字节数组转换为字符串。
var str = "0011111110110101001111110110111100111111110110110011111101101111";
var byteArray = Enumerable.Range(0, str.Length / 8)
.Select(x => Convert.ToByte(str.Substring(x * 8, 8), 2)).ToArray();
var convertedString = Encoding.ASCII.GetString(byteArray);
对于8位
Encoding enc = Encoding.GetEncoding(1252);
var convertedString = enc.GetString(byteArray);
输出
?µ?o?Û?o