通过使用以下代码,我设法解码给定的十六进制字符串。在C#中,使用其库函数,我可以将十六进制值解码为ASCII,Unicode,Big-endian Unicode,UTF8,UTF7,UTF32。能告诉我如何将十六进制字符串转换为其他解码方式,如ROT13,UTF16,西欧,HFS Plus等。
{
string hexString = "68656c6c6f2c206d79206e616d6520697320796f752e";
byte[] dBytes = StringToByteArray(hexString);
//To get ASCII value of the hex string.
string ASCIIresult = System.Text.Encoding.ASCII.GetString(dBytes);
MessageBox.Show(ASCIIresult, "Showing value in ASCII");
//To get the Unicode value of the hex string
string Unicoderesult = System.Text.Encoding.Unicode.GetString(dBytes);
MessageBox.Show(Unicoderesult, "Showing value in Unicode");
}
public static byte[] StringToByteArray(String hex)
{
int NumberChars = hex.Length / 2;
byte[] bytes = new byte[NumberChars];
using (var sr = new StringReader(hex))
{
for (int i = 0; i < NumberChars; i++)
bytes[i] =
Convert.ToByte(new string(new char[2] { (char)sr.Read(), (char)sr.Read() }), 16);
}
return bytes;
}
答案 0 :(得分:1)
您可以通过接受代码页或编码名称的方法Encoding.GetEncoding获取其他编码对象。 e.g。
//To get the UTF16 value of the hex string
string UTF16Result = System.Text.Encoding.GetEncoding("utf-16").GetString(dBytes);
MessageBox.Show(UTF16Result , "Showing value in UTF16");
答案 1 :(得分:0)
string utf16string = Encoding.GetEncoding("UTF-16").GetString(dBytes);
MessageBox.Show(utf16string , "Showing value in UTF-16");
查看可能的Code Page解码样式。
并使用此片段将字符串转换为byte []
public static byte[] StringToByteArray(String hexstring)
{
var bytes= new byte[hexstring.Length / 2];
for (int i = 0, j = 0; i < hexstring.Length; i += 2, j++)
bytes[j] = Convert.ToByte(hexstring.Substring(i, 2), 0x10);
return bytes;
}