Oracle FAQ Your Portal to the Oracle Knowledge Grid
HOME | ASK QUESTION | ADD INFO | SEARCH | E-MAIL US
 

Home -> Community -> Usenet -> c.d.o.misc -> Re: Does anyone know how to convert from decimal to hex???

Re: Does anyone know how to convert from decimal to hex???

From: Thomas Kyte <tkyte_at_us.oracle.com>
Date: 1997/06/20
Message-ID: <33aa6b7f.1368087@newshost>#1/1

On 19 Jun 1997 21:16:05 GMT, tcbracey_at_st.usm.edu (Timothy C. Bracey) wrote:

>I'm wokring on a project that requires me to have hex values. Currently they
>are stored as decimal. Does anyone know a way of converting from dec. to
>hex. without having to use or write some pro C code?
>
>--
>---------------
>Timothy Corey Bracey
>Southern Station Box 4591
>University of Southern Mississippi
>Hattiesburg, MS 39406
>E-Mail: tcbracey_at_sushi.st.usm.edu
>Campus Phone: 601-266-1037

Here are some functions that convert base N to base M

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

	l_str	varchar2(255) default NULL;
	l_num	number	default p_dec;
	l_hex	varchar2(16) default '0123456789ABCDEF';
begin
	if ( trunc(p_dec) <> p_dec OR p_dec < 0 ) then
		raise PROGRAM_ERROR;
	end if;
	loop
		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';
begin
	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
begin

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

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

        return to_base( p_dec, 8 );
end to_oct;
/

set arraysize 1
column x format a10
column y format 9999999

select rownum, to_hex(rownum) x, to_bin(rownum) x, to_oct(rownum) x from all_users;
select rownum, to_dec(to_hex(rownum),16) Y,

			   to_dec(to_bin(rownum),2 ) y, 
			   to_dec(to_oct(rownum),8) y
from all_users;



Thomas Kyte
tkyte_at_us.oracle.com
Oracle Government
Bethesda MD

http://govt.us.oracle.com/ -- downloadable utilities



Opinions are mine and do not necessarily reflect those of Oracle Corporation Received on Fri Jun 20 1997 - 00:00:00 CDT

Original text of this message

HOME | ASK QUESTION | ADD INFO | SEARCH | E-MAIL US