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.
UNHEX() function in MySQL is used to convert the Hexadecimal number into the bytes represented by the Number. The value returned by it is a binary string. Parameter : Required. str : It is a string which is to be converted into the byte represented by the number.
MySQL CONV() Function The CONV() function converts a number from one numeric base system to another, and returns the result as a string value. Note: This function returns NULL if any of the parameters are NULL. Tip: Also look at the BIN() function.
0x denotes that the value is binary, which is displayed using hex values. What you have is already hex values. The only way to get rid of the 0x is to convert it to a string as I showed in my answer.
HEX() : This function in MySQL is used to return an equivalent hexadecimal string value of a string or numeric Input. If the input is a string then each byte of each character in the string is converted to two hexadecimal digits.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With