[英]convert list<char> that represent binary string into ASCII C#
I have a list of chars that represents a binary string. 我有一个代表二进制字符串的字符列表。
List<char> myCharList = new List<char>();
For example, the charList holds the ascii H which represented by the binary sequence: 01001000 例如,charList保留由二进制序列01001000表示的ascii H
I try to convert this List into ASCII so I can show it in a Text Block. 我尝试将此列表转换为ASCII,以便可以在文本块中显示它。
Thanks 谢谢
try this 尝试这个
string binary = "01001000";
string result = Encoding.ASCII.GetString(binary.SplitByLength(8).Select(x => Convert.ToByte(x, 2)).ToArray());
UPDATE : SplitByLength: 更新 :SplitByLength:
public static IEnumerable<string> SplitByLength(this string str, int maxLength)
{
for (int index = 0; index < str.Length; index += maxLength)
{
yield return str.Substring(index, Math.Min(maxLength, str.Length - index));
}
}
another approach without linq 没有linq的另一种方法
string binary = "01001000";
var list = new List<Byte>();
for (int i = 0; i < binary.Length; i += 8)
{
if (binary.Length >= i + 8)
{
String t = binary.Substring(i, 8);
list.Add(Convert.ToByte(t, 2));
}
}
string result = Encoding.ASCII.GetString(list.ToArray()); // H
this should give you byte representation of an ASCII binary string: 这应该为您提供ASCII二进制字符串的字节表示形式:
static void Main(string[] args)
{
List<char> chars = new List<char> {'1', '0', '0', '0', '0','0','1'};
chars.Reverse();
int t = 0;
for (int i = 0; i < chars.Count; i++)
{
if (chars[i] == '1') t += (int)Math.Pow(2, i);
}
Console.WriteLine("{0} represents {1}",t,(char)t );
Console.Read();
}
this should give you ASCII representations of bytes. 这应该为您提供字节的ASCII表示形式。 Remember that on each system the sizes of a char can differ, so this code will use the systems default size for a char:
请记住,在每个系统上,char的大小可以不同,因此此代码将使用char的系统默认大小:
static void Main(string[] args)
{
List<char> chars = new List<char> {'A', 'E', 'L', 'L', 'O'};
foreach (var c in chars)
{
string s = "";
for (int i = 0; i < (sizeof(char) * 8); i++)
{
s = (1 & ((byte)c >> i)) + s;
}
Console.WriteLine("{0} represents {1}",c,s );
}
Console.Read();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.