将整数连接成二进制字符串并返回

时间:2012-12-12 15:11:52

标签: mysql casting

我想在二进制字符串中存储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   |
+------+------+

有什么不那么冗长吗?如果不是这些功能如何进行转换?

1 个答案:

答案 0 :(得分:0)

将整数连接成二进制字符串的函数:

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 |
+------+------+