【发布时间】: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