Oracle 中的进制转换
Table of Contents
1 进制名
进制 | 英文全名 | 缩写 |
---|---|---|
2 | binary | B |
8 | octal | O |
10 | Decimal | D |
16 | hexadecimal | H |
2 10进制与16进制互相转换
2.1 10进制转换为16进制
10 进制转换为16进制是通过to_char 来实现的:
SQL> col hex for a20 SQL> select trim(to_char(109834,'xxxxxx')) as hex from dual; HEX -------------------- 1ad0a
2.2 16进制转换为10进制
16进制转换为10进制可以通过to_number来实现:
SQL> col dec for 999999 SQL> select to_number('1ad0a','xxxxxxxx') as dec from dual; DEC ------- 109834
3 2进制与10进制互相转换
3.1 2进制转10进制
从Oracle9i开始,提供函数bin_to_num进行2进制到10进制的转换
SQL> select bin_to_num(1,0,1,0,1,1) from dual; BIN_TO_NUM(1,0,1,0,1,1) ----------------------- 43
3.2 10进制转2进制
oracle 没有提供10进制转2进制的函数,不过可以自己写,下面是偷的别人的,
CREATE OR REPLACE FUNCTION NUM_to_BIn(V_NUM NUMBER) RETURN VARCHAR IS V_RTN VARCHAR(2000); V_N1 NUMBER; V_N2 NUMBER; BEGIN V_N1 := ABS(V_NUM); --如果为正数 IF SIGN(V_NUM) > 0 THEN LOOP V_N2 := MOD(V_N1, 2); V_N1 := ABS(TRUNC(V_N1 / 2)); V_RTN := TO_CHAR(V_N2) || V_RTN; EXIT WHEN V_N1 = 0; END LOOP; --dbms_output.put_line('正数结果'||V_RTN); --补全32位高位0 SELECT lpad(V_RTN,32,0) INTO V_RTN FROM dual; --dbms_output.put_line('正数补全结果'||V_RTN); ELSE --转换为二进制同时按位取反 LOOP V_N2 := MOD(V_N1, 2); IF V_N2 = 1 THEN V_N2 := 0; ELSIF V_N2 = 0 THEN V_N2 := 1; END IF; V_N1 := ABS(TRUNC(V_N1 / 2)); V_RTN := TO_CHAR(V_N2) || V_RTN; EXIT WHEN V_N1 = 0; END LOOP; --dbms_output.put_line('负数结果'||V_RTN); --补全32位高位1 SELECT lpad(V_RTN,32,1) INTO V_RTN FROM dual; --dbms_output.put_line('负数补全1结果'||V_RTN); --二进制转换为10机制,同时+1 SELECT SUM(data1) + 1 INTO V_N1 FROM (SELECT substr(V_RTN, rownum, 1) * power(2, length(V_RTN) - rownum) data1 FROM dual CONNECT BY rownum <= length(V_RTN)); -- dbms_output.put_line('转换为十进制数结果'||V_RTN); ----转换为二进制 LOOP V_N2 := MOD(V_N1, 2); V_N1 := ABS(TRUNC(V_N1 / 2)); V_RTN := TO_CHAR(V_N2) || V_RTN; EXIT WHEN V_N1 = 0; END LOOP; --dbms_output.put_line('负数转换结果'||V_RTN); --补全32位高位0 SELECT lpad(V_RTN,32,0) INTO V_RTN FROM dual; --dbms_output.put_line('负数补全0结果'||V_RTN); END IF; RETURN V_RTN; END; /
原网页如下: https://blog.csdn.net/java3344520/article/details/6684814
示例
SQL> select num_to_bin(-1) from dual; NUM_TO_BIN(-1) -------------------------------------------------------------------------------- 11111111111111111111111111111111 SQL> select num_to_bin(1) from dual; NUM_TO_BIN(1) -------------------------------------------------------------------------------- 00000000000000000000000000000001
Created: 2019-07-28 Sun 19:47