且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在C#中将Hex字符串转换为普通字符串

更新时间:2023-02-12 15:31:53

解决方案4中的Rob通常是正确的...但是,如果 string是每个字符编码一个字节的十六进制编码(例如ASCII)然后它应该是正确的,具有奇数个字节。

而不是将字节转储到char数组中你应该使用正确的 System.Text.Encoding object。

Rob in Solution 4 is generally correct... However, if the string is hex encoded from a one byte per character encoding (ASCII for example) then it should be correct with an odd number of bytes.
Instead of dumping the bytes into the char array you should use the correct System.Text.Encoding object.
public static string HextoString(string InputText)
{
 
    byte[] bb = Enumerable.Range(0, InputText.Length)
                     .Where(x => x % 2 == 0)
                     .Select(x => Convert.ToByte(InputText.Substring(x, 2), 16))
                     .ToArray();
    return System.Text.Encoding.ASCII.GetString(bb);
    // or System.Text.Encoding.UTF7.GetString
    // or System.Text.Encoding.UTF8.GetString
    // or System.Text.Encoding.Unicode.GetString
    // or etc.
}


参考link [ ^ ]它正常工作。
refer answer 4 in link[^] it is working.


喜欢这样





Like so


static void Main()
{
    byte[] data = FromHex("47-61-74-65-77-61-79-53-65-72-76-65-72");
    string s = Encoding.ASCII.GetString(data); // GatewayServer
}
public static byte[] FromHex(string hex)
{
    hex = hex.Replace("-", "");
    byte[] raw = new byte[hex.Length / 2];
    for (int i = 0; i < raw.Length; i++)
    {
        raw[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
    }
    return raw;
}
















or


string hexValues = "48 65 6C 6C 6F 20 57 6F 72 6C 64 21";
string[] hexValuesSplit = hexValues.Split(' ');
foreach (String hex in hexValuesSplit)
{
    // Convert the number expressed in base-16 to an integer.
    int value = Convert.ToInt32(hex, 16);
    // Get the character corresponding to the integral value.
    string stringValue = Char.ConvertFromUtf32(value);
    char charValue = (char)value;
    Console.WriteLine("hexadecimal value = {0}, int value = {1}, char value = {2} or {3}",
                        hex, value, stringValue, charValue);
}