Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert hex to binary in MySQL

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.

like image 625
Dels Avatar asked Apr 18 '11 06:04

Dels


People also ask

How to unhex MySQL?

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.

How to use CONV in MySQL?

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.

What is 0x in sql?

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.

What is hex in MySQL?

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.


2 Answers

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).

like image 27
picmate 涅 Avatar answered Oct 08 '22 21:10

picmate 涅


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.

like image 123
ypercubeᵀᴹ Avatar answered Oct 08 '22 21:10

ypercubeᵀᴹ