Convert hex to binary in MySQL

2020-02-27 08:19发布

问题:

Currently I search a function in MySQL to do conversion between hex string to binary representation, example:

0000 -> 0000000000000000
00AA -> 0000000010101010
FFFF -> 1111111111111111

I have already tried

UNHEX('00AA')
CAST('00AA' AS BINARY)
CONVERT('00AA', BINARY)

but didn't get the results I want.

回答1:

Use CONV() function:

CONV(string, 16, 2)

To have length according to input:

LPAD(CONV(string, 16, 2), LENGTH(string)*4, '0')

As CONV() works with 64-bit precision, you can't have more than 64 bits converted, so you can use this as well:

LPAD(CONV(string, 16, 2), 64, '0')

and you should check that LENGTH(string) <= 16 or you may get erroneous results.



回答2:

UNHEX('hex string')

Would interpret each pair of characters in a string passed into the function as two hex characters and try to convert that to a binary number (binary format in mysql). This way, you can convert a string to binary. However, this won't display the content as a string of binary digits. Rather, each 2 bytes in the resulting string converted to the specific character encoding (for example utf8).