开发者

How to convert a byte string to a number in Oracle?

开发者 https://www.devze.com 2023-03-12 23:28 出处:网络
I want to convert a byte string like \'1001\' to the integer value 9, is there a standard function for that in Oracle ?

I want to convert a byte string like '1001' to the integer value 9, is there a standard function for that in Oracle ?

BTW I found a custom solution on http://www开发者_开发技巧.orafaq.com/wiki/Binary


I was trying this on Oracle using CONNECT BY to convert binary to decimal in simple SELECT statement. Finally got the desired output using below code.

WITH INPUT AS
(SELECT REVERSE('&N') AS X FROM DUAL)
SELECT SUM(TO_NUMBER(SUBSTR(X,LEVEL,1)*POWER(2,LEVEL-1))) AS OUTPUT
FROM INPUT CONNECT BY LEVEL<=LENGTH(X);


AFAIK there's no a built in function in Oracle for that, though you can use solution provided int he link in your post


See here for library from Tom Kyte for doing these type conversions.

In this case, you'd have:

select to_dec('1001', 2) from dual;


"Is there a standard function for that in Oracle?"

There is BIN_TO_NUM which converts a bit vector to its equivalent number.

SET SERVEROUTPUT ON;
DECLARE
  i VARCHAR2(100) := '1001';
  o INT;
BEGIN
  i:= TRIM(BOTH ',' FROM REPLACE(REPLACE(i, '1', '1,'),'0','0,')); 
  EXECUTE IMMEDIATE 'SELECT BIN_TO_NUM('|| i || ') FROM dual' INTO o;
  DBMS_OUTPUT.put_line(i || ' => ' || o);
END;
/

Result:

1,0,0,1 => 9

DBFiddle Demo

0

精彩评论

暂无评论...
验证码 换一张
取 消