在 MySQL 中将十六进制转换为二进制

2022-01-09 00:00:00 binary sql hex mysql

目前我在 MySQL 中搜索一个函数来进行十六进制字符串到二进制表示之间的转换,例如:

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

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

我已经试过了

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

但没有得到我想要的结果.

but didn't get the results I want.

推荐答案

使用CONV()函数:

CONV(string, 16, 2)

根据输入获得长度:

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

由于 CONV() 以 64 位精度工作,因此您不能转换超过 64 位,因此您也可以使用它:

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

你应该检查 LENGTH(string) <= 16 否则你可能会得到错误的结果.

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

相关文章