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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5699424/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 19:33:13  来源:igfitidea点击:

Convert hex to binary in MySQL

mysqlsqlbinaryhex

提问by Dels

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

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

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.

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

回答by ypercube??

Use CONV()function:

使用CONV()功能:

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:

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

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

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

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

回答by u557022

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

将传递给函数的字符串中的每一对字符解释为两个十六进制字符,并尝试将其转换为二进制数(mysql 中的二进制格式)。这样,您可以将字符串转换为二进制。但是,这不会将内容显示为一串二进制数字。而是将结果字符串中的每 2 个字节转换为特定的字符编码(例如 utf8)。