gpt4 book ai didi

c# - 如何适本地从字符串中获取字节?

转载 作者:太空狗 更新时间:2023-10-30 01:08:49 25 4
gpt4 key购买 nike

我有一个字符串变量,我通过以下循环从中获取以下字节:

Bytes I get: 1e 05 55 3c *e2 *91 6f 03 *fe 1a 1d *f4 51 6a 5e 3a *ce *d1 04 *8c 

With that loop:

byte[] temp = new byte[source.Length];
string x = "";
for (int i = 0;i != source.Length;i++)
{
temp[i] = ((byte) source[i]);
}

现在我想简化该操作并使用 Encoding 的 GetBytes。问题是我无法适应适当的编码。例如我有几个字节不正确:

Encoding.ASCII.GetBytes(source):    1e 05 55 3c *3f *3f 6f 03 *3f 1a 1d *3f 51 6a 5e 3a *3f *3f 04 *3f
Encoding.Default.GetBytes(source): 1e 05 55 3c e2 3f 6f 03 3f 1a 1d f4 51 6a 5e 3a ce 4e 04 3f

如何摆脱该循环并使用 Encoding 的 GetBytes?

总结如下:

Loop(correct bytes):                1e 05 55 3c *e2 *91 6f 03 *fe 1a 1d *f4 51 6a 5e 3a *ce *d1 04 *8c 

Encoding.ASCII.GetBytes(source): 1e 05 55 3c *3f *3f 6f 03 *3f 1a 1d *3f 51 6a 5e 3a *3f *3f 04 *3f
Encoding.Default.GetBytes(source): 1e 05 55 3c e2 3f 6f 03 3f 1a 1d f4 51 6a 5e 3a ce 4e 04 3f

谢谢!

添加:

我有一个十六进制字符串输入,例如:“B1807869C20CC1788018690341”然后我使用以下方法将其转换为字符串:

private static string hexToString(string sText)
{
int i = 0;
string plain = "";
while (i < sText.Length)
{
plain += Convert.ToChar(Convert.ToInt32(sText.Substring(i, 2), 16));
i += 2;
}
return plain;
}

最佳答案

您的 hexToString 正在将字节值(通过十六进制)直接传输到 0-255 范围内的 unicode 代码点。碰巧,这与代码页 28591 相关,因此如果您使用:

Encoding enc = Encoding.GetEncoding(28591);

并使用that enc,你应该得到正确的数据;然而,这里更重要的一点是二进制数据与文本数据不同,您不应该使用 string 来保存任意二进制数据。

关于c# - 如何适本地从字符串中获取字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8338477/

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