Display binary(16) column as hex in mysql

早过忘川 提交于 2020-04-07 04:13:32

问题


Given a binary(16) column, how do I display its value as a hexadecimal number? I've been experimenting in the console a little below, and I'm not getting the results I expect. Could it be that I'm not converting numbers to binary properly?

I have the following sample query: select hex(cast(10 as binary)),

but the output is rather unexpected: 3130.

Basically, it appears to just take the decimal representation of the number, and insert a 3 digit before each digit, e.g. 2 -> 32, 22 -> 3232, 678 -> 363738, etc.

If I specify a length for the binary data type (e.g. binary(16)), I get the same behavior, except that it gets padded on the right with the required number of 0s.

Obviously, that's not what I'm looking for. What am I missing?

EDIT: just tried convert(678, binary) instead of cast, same behavior.


回答1:


Why make things complicated? I just use this to display the value of a BINARY(16) column:

SELECT HEX(colname);




回答2:


Use CONV function

-- convert '10000'(16 in binary) in hex
SELECT CONV('10000',2,16);
-- Ouput: 10


-- convert 'F' in hex to binary
SELECT CONV('F',16,2);
-- Output: 1111

Hexadecimal to binary table

Hexadecimal Binary
0         0000
1         0001
2         0010
3         0011
4         0100
5         0101
6         0110
7         0111
8         1000
9         1001
A         1010
B         1011
C         1100
D         1101
E         1110
F         1111
10       10000
11       10001
...



回答3:


Just try this and you will clear your mind:

select conv(cast(10 as binary), 10, 16);

BINARY data type is treated as decimal string by default



来源:https://stackoverflow.com/questions/40980281/display-binary16-column-as-hex-in-mysql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!