4

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

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

4

1 回答 1

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 |
+------+------+
于 2012-12-13T14:16:34.053 回答