2012-12-12 49 views
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 | 
+------+------+ 

有什麼不太詳細的?如果不是這些功能將如何做這些轉換?

回答

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 | 
+------+------+ 
相關問題