从十六进制值的字符串转换.NET成Unicode字符(支持不同的代码页) [英] .NET Convert from string of Hex values into Unicode characters (Support different code pages)

查看:211
本文介绍了从十六进制值的字符串转换.NET成Unicode字符(支持不同的代码页)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的十六进制值...

I have a string of Hex values...

String hexString = "8A65";



我需要这个字符串转换成它们的Unicode等效。最棘手的部分是,我需要支持不同的代码页和一些代码的网页有'8A65'=一个字符,而其它代码页将其转换成两个字符。

I need to convert this string into their Unicode equivalents. The tricky part is that I need to support different code pages and some code pages have '8A65' = one character whereas other code pages would convert it into two characters.

我有哪个代码页中我将使用,直到我需要进行转换的先验知识。

I have no prior knowledge of which code page I will be using until I need to perform the conversion.

我已经试过各种东西,如

I've tried all sorts of stuff such as

byte[] original = Encoding.Unicode.GetBytes(hexString);
byte[] conv= Encoding.Convert(Encoding.Unicode, Encoding.GetEncoding(932), orig);
char[] chars = Encoding.GetEncoding(932).GetChars(conv);

请注意:代码页932日

Note: code page 932 is Japanese

SOLUTION

string hexString = "8A65";
int length = hexString.length;
byte[] bytes = new byte[length / 2];

for (int i = 0; i < length; i += 2)
{
    bytes[i / 2] = Convert.ToByte(hexString.Substring(i, 2), 16);
}

char[] chars = Encoding.GetEncoding(932).GetChars(bytes);

感谢您pstrjds,你是一个生命的救星!

Thank you pstrjds, you are a life saver!

推荐答案

您需要将十六进制字符串转换为字节(见的 SO帖子)。路过十六进制字符串到编码之一将其转换为字节只是给你的字节相当于这些字符。我假设你想要的是这4字符串为两个字节,所以解码十六进制字节,然后你可以使用解码字节得到一个字符串的编码。

You need to convert the hex string to bytes (see SO post). Passing the hex string into one of the encodings to convert it to bytes just gives you the byte equivalent of those characters. I am assuming what you want is the two bytes that the 4 character string represents, so decode the hex to bytes and then you can use the encoding on the decoded bytes to get back a string.

Encoding.{YourEncoding}.GetChars(hexBytes);

这篇关于从十六进制值的字符串转换.NET成Unicode字符(支持不同的代码页)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆