Oracle里二进制与十进制的相互转换

in #oracle6 years ago

Oracle里有内建函数bin_to_num可以将二进制数转换为十进制数,但这个函数的入参是个数不定的0或1:
[sql] view plaincopy
SELECT BIN_TO_NUM (1, 1, 1, 1, 0, 1, 1) FROM DUAL;

有时候入参使用一个二进制字符串会更加方便,另外Oracle本身没有提供num_to_bin这样将十进制转换成二进制的函数,于是写了两个自定义函数,算法很简单,不过这次追求的是用最少的代码实现。
[sql] view plaincopy
CREATE OR REPLACE FUNCTION bin_to_num1 (p_binstr VARCHAR2) RETURN NUMBER
IS
l_len NUMBER := LENGTH (p_binstr);
r_num NUMBER := 0;
BEGIN
FOR i IN 1 .. l_len LOOP
IF SUBSTR (p_binstr, i, 1) = '1' THEN
r_num := r_num + POWER (2, l_len - i);
END IF;
END LOOP;

RETURN r_num;
END bin_to_num1;
/
[sql] view plaincopy
SELECT bin_to_num1 ('1111011') FROM DUAL;
[sql] view plaincopy
CREATE OR REPLACE FUNCTION num_to_bin (p_num NUMBER) RETURN VARCHAR2
IS
r_binstr VARCHAR2 (32767);
l_num NUMBER := p_num;
BEGIN
WHILE l_num != 0 LOOP
r_binstr := TO_CHAR (MOD (l_num, 2)) || r_binstr;
l_num := TRUNC (l_num / 2);
END LOOP;

RETURN r_binstr;
END num_to_bin;
/
[sql] view plaincopy
SELECT num_to_bin (123) FROM DUAL;

Coin Marketplace

STEEM 0.27
TRX 0.21
JST 0.038
BTC 96276.55
ETH 3627.68
SBD 3.80