# 用SQL， 十进制转二进制的方法

问：1234 转二进制，一个ＳＱＬ如何写？

---------------------------------------------------------------

WITH T (A,B) AS (
SELECT FLOOR(1234/2), MOD(1234,2)  FROM DUAL
UNION ALL
SELECT FLOOR(T.A/2) , MOD(T.A,2)
FROM  T
WHERE T.A > 0
)
SELECT LISTAGG(B,'')WITHIN GROUP(ORDER BY A ) BIN FROM T;

-----------------------------------------------------------------------

SELECT LTRIM(BIN,'0') BIN FROM (SELECT 1234 N FROM DUAL)
MODEL
DIMENSION BY (0 A)
MEASURES(N,CAST('' AS VARCHAR2(2000)) BIN)
RULES ITERATE(1000) UNTIL(ITERATION_NUMBER = CEIL(LOG(2,1234)) )(
BIN[0] = TO_CHAR(MOD(N[0],2))||BIN[0]
,N[0] = FLOOR(N[0]/2)
);

-----------------------------------------------------------------------

SELECT LTRIM(REVERSE(REPLACE(SYS_CONNECT_BY_PATH(BITAND(1234,POWER(2,LEVEL-1))/POWER(2,LEVEL-1),','),',')),'0')
FROM DUAL
WHERE CONNECT_BY_ISLEAF = 1
CONNECT BY LEVEL <= CEIL(LOG(2,1234))+1;

select replace(sys_connect_by_path(decode(bitand(8, power(2, ceil(log(2, 8)) - level)),
0,
'0',
'1'),
'.'),'.',null)
from dual
where level = ceil(log(2, 1234))
connect by level <= ceil(log(2, 8));

-----------------------------------------------------------------------

SELECT LTRIM(
REPLACE(REPLACE(REPLACE(REPLACE(
REPLACE(REPLACE(REPLACE(REPLACE(
REPLACE(REPLACE(REPLACE(REPLACE(
REPLACE(REPLACE(REPLACE(REPLACE(TO_CHAR(1234,'FMXXXXXX')
,'0','0000')
,'1','0001')
,'2','0010')
,'3','0011')
,'4','0100')
,'5','0101')
,'6','0110')
,'7','0111')
,'8','1000')
,'9','1001')
,'A','1010')
,'B','1011')
,'C','1100')
,'D','1101')
,'E','1110')
,'F','1111'),'0')
FROM DUAL ;

--------------------------------------------------------------------------------

select ltrim(translate(ltrim(dump(convert(translate(to_char(1234, 'FMXXXXXXXX'),
'0123456789ABCDEF',
'热壬纫扔扇缮梢捎胰疑乙矣尤由右佑'),
'zhs16gbk')),
'TypLen =0123456789'),
'123456789, :',
'1'),
'0')
from dual;

--------------------------------------------------------------------------------

select ltrim(translate(asciistr(translate(to_char(1234, 'FMXXXXXX'),
'0123456789ABCDEFG',
'业丛个丫会伛伪伫帚帛帪師弚弛弪弫')),
'4E1A5F2B\',
'00001111'),
'0')
from dual;

• 博文量
10
• 访问量
9686