Skip to Main Content

SQL & PL/SQL

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

How to convert negative base 10 to base 16?

donovan7800May 23 2012 — edited May 24 2012
Hi,

Finding this to be harder than expected. Originally tried the following:
CREATE OR REPLACE FUNCTION num2hex (N IN NUMBER) RETURN VARCHAR2 IS
  H  VARCHAR2(64) :='';
  N2 INTEGER      := N;
BEGIN
  LOOP
     SELECT RAWTOHEX(CHR(N2))||H
     INTO   H
     FROM   dual;
 
     N2 := TRUNC(N2 / 256);
     EXIT WHEN N2=0;
  END LOOP;
  RETURN H;
END num2hex;
Works for positive numbers, but not negative numbers.

I was told the high level process to do this for a number (i.e. -1208728914) was:
1) Remove the negative: 1208728914
2) Convert from b10 to binary: utl_raw.cast_from_number(1208728914)
3) Perform 2s complement: utl_raw.bit_complement
4) add 1
5) convert from binary back to hex: rawtohex?

I know for the above negative number the leftmost 8 hex digits should be: B7F442AE but I am not getting that.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jun 21 2012
Added on May 23 2012
5 comments
1,259 views