1

I have a text file with different characters and want to convert each character in HEX values. I am using Encoding.ASCII.GetBytes() and then converting each byte to hex.

But the result is not correct each time. Some characters does not show their correct hex values and expected. For example the charcter 'î' should return the expected hex value 8C according to the provided document, but the code below returns 3F.

The code which is used is as following:

string myBytes = String.Empty;
string dp = "î";                 
byte[] bdp = Encoding.ASCII.GetBytes(dp);
foreach (byte b in bdp)
{
myBytes += b.ToString("x") + " ";
}
4

1 回答 1

5

试试这个方法

string myBytes = String.Empty;
string dp = "î";                 

//byte[] bdp = Encoding.ASCII.GetBytes(dp);
byte[] bdp = Encoding.GetEncoding(437).GetBytes(dp);  //  <----- NOTE 437

foreach (byte b in bdp)
{
    myBytes += b.ToString("x") + " ";
}

参考:http ://en.wikipedia.org/wiki/Code_page_437

编辑:

ASCII 仅在 0-127 之间定义。c# ASCII 编码只能处理这么多字符。î性格不在那些。您可能正在谈论ASCII,因为它在旧的 MS-DOS 和旧的 IBM-PC 中。这些机器理解的字符集略有不同。基础(31-127)与现代 ASCII 甚至 Unicode 相同。但其他不同。这种字符方言称为 CODE-PAGE-437。

于 2013-11-12T08:44:55.013 回答