gpt4 book ai didi

c# - 将位串转换为字符

转载 作者:太空宇宙 更新时间:2023-11-03 13:25:15 25 4
gpt4 key购买 nike

我正在尝试将位串转换为 8 位的 ASCII 字符(每 8 位 = 1 个 ASCII 字符)。

        public string BitsToChar(string InpS)
{
string RetS = "";
for (int iCounter = 0; iCounter < InpS.Length / 8; iCounter++)
RetS = System.String.Concat(RetS, (char)Convert.ToByte(InpS.Substring(iCounter * 8, 8)), 2);
return RetS;
}

它抛出 System.OverflowException:值对于无符号字节来说太大或太小。

我不清楚为什么二进制字符串的 8 位部分对于 8 位字节类型来说可能太小或太大。

有什么想法吗?谢谢。

最佳答案

尝试这样的事情:

    private static Char ConvertToChar(String value) {
int result = 0;

foreach (Char ch in value)
result = result * 2 + ch - '0';

return (Char) result;
}

public string BitsToChar(string value) {
if (String.IsNullOrEmpty(value))
return value;

StringBuilder Sb = new StringBuilder();

for (int i = 0; i < value.Length / 8; ++i)
Sb.Append(ConvertToChar(value.Substring(8 * i, 8)));

return Sb.ToString();
}

...

   String result = BitsToChar("010000010010000001100010"); // <- "A b"

关于c# - 将位串转换为字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22653183/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com