Re: Byte to bit conversion

From: Thomas Kyte <>
Date: Fri, 28 May 1999 12:40:18 GMT
Message-ID: <>

A copy of this was sent to "Venkat Narayanan" <> (if that email address didn't require changing) On Fri, 28 May 1999 17:33:36 +0800, you wrote:

>Hi. I am looking for a way to convert a one character byte data in Oracle to
>the independent bits represented by the value in the character data. That
>is, the one character data should become 8 character fields with each field
>having 0 or 1 depending upon the bit pattern of the source character data.
>Is there a way to do this in PL/SQL ? Please reply to

the following set of routine will help do that. after you have them installed, you can do things like:

SQL> select to_bin( ascii('A') ) from dual;



SQL> select to_hex( ascii('A') ) from dual;



create or replace function to_base( p_dec in number, p_base in number ) return varchar2

	l_str	varchar2(255) default NULL;
	l_num	number	default p_dec;
	l_hex	varchar2(16) default '0123456789ABCDEF';
	if ( trunc(p_dec) <> p_dec OR p_dec < 0 ) then
	end if;
		l_str := substr( l_hex, mod(l_num,p_base)+1, 1 ) || l_str;
		l_num := trunc( l_num/p_base );
		exit when ( l_num = 0 );
	end loop;
	return l_str;

end to_base;

create or replace function to_dec
( p_str in varchar2,
  p_from_base in number default 16 ) return number is

	l_num   number default 0;
	l_hex   varchar2(16) default '0123456789ABCDEF';
	for i in 1 .. length(p_str) loop
		l_num := l_num * p_from_base + instr(l_hex,upper(substr(p_str,i,1)))-1;
	end loop;
	return l_num;

end to_dec;
show errors

create or replace function to_hex( p_dec in number ) return varchar2 is

        return to_base( p_dec, 16 );
end to_hex;
create or replace function to_bin( p_dec in number ) return varchar2 is

        return to_base( p_dec, 2 );
end to_bin;
create or replace function to_oct( p_dec in number ) return varchar2 is

        return to_base( p_dec, 8 );
end to_oct;

See for my column 'Digging-in to Oracle8i'...  

Thomas Kyte
Oracle Service Industries
Reston, VA USA

Opinions are mine and do not necessarily reflect those of Oracle Corporation
Received on Fri May 28 1999 - 14:40:18 CEST

Original text of this message