【问题标题】:Encoding issue with String to Bytes conversion字符串到字节转换的编码问题
【发布时间】:2013-12-24 10:45:51
【问题描述】:

我正在尝试将字符串转换为字节,反之亦然..我已经在此站点上看到了将字符串转换为字节数组的上一个问题..但我的问题是别的

这是我的代码

byte[] btest = new byte[2];
btest[0] = 0xFF;
btest[1] = 0xAA;
UTF8Encoding enc = new UTF8Encoding();
string str = enc.GetString(btest); //here i get a string with values str = '��'

//I had a byte array of size 2 with the above contents
//Here i am trying to convert the string to byte array
byte [] bst = enc.GetBytes(str); //On this step i get a byte array of size 6 
//and bst array contents as {239,191,189,239,191,189}

//In this step i try to convert the value back to btest array by taking the index
btest[0] = Convert.ToByte(str[0]); //on this line i get an exception
//Exception : Value was either too large or too small for an unsigned byte.
btest[1] = Convert.ToByte(str[1]);

GetBytes 不应该返回一个大小为 2 的字节数组,我在做什么错? 我希望 bst[0] 包含我分配给 btest[0] 的相同值。

谢谢

【问题讨论】:

  • 请尽量在您的问题标题中更加清晰。 :)

标签: c# character-encoding


【解决方案1】:

您的原始字节输入不是有效的 UTF-8(请参阅 here),因为它不代表任何 unicode 代码点。结果,无效数据被转换为�。最后,这是一个和其他任何字符一样的字符,因此如果您尝试将其转换回字节,它不会生成初始错误的字节序列,而是生成表示该 unicode 代码点的正确字节序列(两次)。

字符不能表示为单个字节,因此Convert.ToByte 会抛出OverflowException

如果您要将原始输入更改为有效的字节序列,例如:

btest[0] = 0xDF;
btest[1] = 0xBF;

您会看到enc.GetBytes(str) 调用实际上再次生成了一个两字节数组。

【讨论】:

    【解决方案2】:

    代码点为0xFF 0xAA的字符在UTF-8编码中无效,因此被转换为

    参考资料:

    【讨论】:

    • 但是当我把它转换回来为什么我没有得到正确的输出??
    • @singh:这是正确的。 str等于��,每一个都用3字节码位表示
    • 实际上我将从这里构造的字符串传递给 c++,但我没有得到正确的值,正如 David Heffernan 在他的回答 stackoverflow.com/questions/20145911/c-sharp-to-c-array/… 中所解释的那样
    • 另一方面,如果我在同一个问题中使用 kunal 的答案,我会得到正确的值
    • @singh:你得到了 2 个解释行为的答案。如果您执行1 + 1,则返回值将是2,而不是5,即使您真的想要它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-22
    • 2019-05-12
    • 2011-10-24
    • 1970-01-01
    • 2016-01-21
    • 2011-04-01
    • 2015-03-15
    相关资源
    最近更新 更多