Saturday, July 12, 2008

To convert an integer to binary string using oracle pl/sql

-- Converts a given decimal number to binary.
-- Ignores decimals - only converts integer portion of a number,
-- but it keeps the sign.

CREATE OR REPLACE FUNCTION f_to_binary ( in_num IN NUMBER )
RETURN NUMBER
IS
ln_max NUMBER := FLOOR ( LN ( ABS ( in_num ) ) / LN(2) );
ln_num NUMBER := ABS ( in_num );
lv_bin VARCHAR2(4000) := '0';
ln_Sign NUMBER;
BEGIN
IF in_num >= 0 THEN
ln_Sign := 1;
ELSE
ln_Sign := -1;
END IF;

FOR i IN REVERSE 0..ln_max
LOOP
IF ln_num >= POWER ( 2, i ) THEN
lv_bin := lv_bin || '1';
ln_num := ln_num - POWER ( 2, i );
ELSE
lv_bin := lv_bin || '0';
END IF;
END LOOP;

RETURN TO_NUMBER ( lv_bin ) * ln_Sign;
END f_to_binary;
/

execute it as follows
SET SERVEROUTPUT ON
declare
out_num NUMBER;
begin
out_num := f_to_binary(10);
DBMS_OUTPUT.PUT_LINE('output = ' ||out_num);
end;
/

Sphere: Related Content

1 comments:

Anonymous said...

Why the function return the same value as '11111' when you call f_to_binary(32) and f_to_binary(31)?