C#中的解码样式

问题描述 投票:2回答:2

通过使用以下代码,我设法解码给定的十六进制字符串。在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;
}  
c# decoding
2个回答
0
投票

通过使用GetEncoding()

 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;
    }  

1
投票

您可以通过Encoding.GetEncoding方法获取其他Encoding对象,该方法接受代码页或编码名称。例如

//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");
© www.soinside.com 2019 - 2024. All rights reserved.