我想在二进制字符串中存储 20 个字节(来自应用程序的整数)。这是我能做的最好的。两个字节只是为了让它更简单。
create table t (bs binary(2));
insert into t (bs) values
(concat(unhex(hex(240)), unhex(hex(40))))
;
select
conv(hex(left(bs, 1)), 16, 10) n1,
conv(hex(mid(bs, 2, 1)), 16, 10) n2
from t;
+------+------+
| n1 | n2 |
+------+------+
| 240 | 40 |
+------+------+
有没有更简洁的?如果不是,函数将如何进行这些转换?
最佳答案
将整数连接成二进制字符串的函数:
create function concat_integers_into_binary(
i1 integer, i2 integer
) returns binary(2) deterministic
return concat(unhex(hex(i1)), unhex(hex(i2)))
insert into t (bs) values
(concat_integers_into_binary(240, 40))
将二进制字符串转换为整数的函数:
create function binary2integer(
bs varbinary(20), position integer
) returns integer deterministic
return conv(hex(substring(bs, position, 1)), 16, 10)
select
binary2integer(bs, 1) n1,
binary2integer(bs, 2) n2
from t;
+------+------+
| n1 | n2 |
+------+------+
| 240 | 40 |
+------+------+
关于mysql - 将整数连接成二进制字符串并返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13842700/