Oracle FAQ | Your Portal to the Oracle Knowledge Grid |
![]() |
![]() |
Home -> Community -> Usenet -> c.d.o.server -> Re: Decimal to Hexa
A copy of this was sent to odabrun_at_hotmail.com ("Odair Brun")
(if that email address didn't require changing)
On Wed, 28 Oct 1998 05:03:48 -0800, you wrote:
>Hi,
>
>I need to convert a decimal field to hexadecimal field. How can I do
>it in
>the %252522select%252522?
>
>Thanks.
>
>
>
> -**** Posted from Supernews, Discussions Start Here(tm) ****-
>http://www.supernews.com/ - Host to the the World's Discussions & Usenet
Here is a series of conversion functions for converting from decimal to any base and vice versa. They are all callable from SQL.
the functions to_base and to_dec are the main 'workhorse' routines. to_base takes a base 10 number in and a base to convert it to and returns the converted string. to_dec takes a string in and the base that string is in and returns the base 10 equivalent number.
Functions to_hex, to_bin, and to_oct are just convienence functions for the most common conversions.....
Once you install these, you'll be able to:
1* select to_hex( 55 ) from dual
SQL> /
TO_HEX(55)
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;
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;
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;
/
Thomas Kyte
tkyte_at_us.oracle.com
Oracle Government
Herndon VA
--
http://govt.us.oracle.com/ -- downloadable utilities
Anti-Anti Spam Msg: if you want an answer emailed to you, you have to make it easy to get email to you. Any bounced email will be treated the same way i treat SPAM-- I delete it. Received on Thu Oct 29 1998 - 08:12:38 CST
![]() |
![]() |