问题描述:

I need to use HEX() in MySQL to get data out of the database and process in C# WinForm code. The binary string needs to be decoded in C#, is there an equivalent UNHEX() function?

From MySQL Doc:

For a string argument str, HEX() returns a hexadecimal string

representation of str where each byte of each character in str is

converted to two hexadecimal digits. (Multi-byte characters therefore

become more than two digits.) The inverse of this operation is

performed by the UNHEX() function.

For a numeric argument N, HEX() returns a hexadecimal string

representation of the value of N treated as a longlong (BIGINT)

number. This is equivalent to CONV(N,10,16). The inverse of this

operation is performed by CONV(HEX(N),16,10).

mysql> SELECT 0x616263, HEX('abc'), UNHEX(HEX('abc'));

-> 'abc', 616263, 'abc' mysql> SELECT HEX(255), CONV(HEX(255),16,10);

-> 'FF', 255

网友答案:

You can use this not-widely-known SoapHexBinary class to parse hex string

string hex = "616263";
var byteArr = System.Runtime.Remoting.Metadata.W3cXsd2001.SoapHexBinary.Parse(hex).Value;
var str = Encoding.UTF8.GetString(byteArr);
网友答案:

After fetching the binary string from the database, you can "unhex" it this way:

public static string Hex2String(string input)
{
    var builder = new StringBuilder();
    for(int i = 0; i < input.Length; i+=2){ //throws an exception if not properly formatted
        string hexdec = input.Substring(i, 2);
        int number = Int32.Parse(hexdec, NumberStyles.HexNumber);
        char charToAdd = (char)number;
        builder.Append(charToAdd);
    }
    return builder.ToString();
}

The method builds a string from the hexadecimal format of the numbers, their char representation being concatenated to the builder branch.

相关阅读:
Top