Hexadecimal

From Oracle FAQ
⧼orafaq-jumptonavigation⧽⧼orafaq-jumptosearch⧽

Hecidecimal (hex) is a numbering system with 16 digits: 0 to 9 and A to F.

Conversion functions

Use the following conversion PL/SQL functions to convert hexadecimal (hex) values to decimal and vice versa:

CREATE OR REPLACE FUNCTION hex2dec (hexval in char) RETURN number IS
  i                 number;
  digits            number;
  result            number := 0;
  current_digit     char(1);
  current_digit_dec number;
BEGIN
  digits := length(hexval);
  for i in 1..digits loop
     current_digit := SUBSTR(hexval, i, 1);
     if current_digit in ('A','B','C','D','E','F') then
        current_digit_dec := ascii(current_digit) - ascii('A') + 10;
     else
        current_digit_dec := to_number(current_digit);
     end if;
     result := (result * 16) + current_digit_dec;
  end loop;
  return result;
END hex2dec;
/

SQL> SELECT hex2dec('AFB2') FROM dual;
HEX2DEC('AFB2')
---------------
          44978
CREATE OR REPLACE FUNCTION dec2hex (N in number) RETURN varchar2 IS
  hexval varchar2(64);
  N2     number := N;
  digit  number;
  hexdigit  char;
BEGIN
  while ( N2 > 0 ) loop
     digit := mod(N2, 16);
     if digit > 9 then 
       hexdigit := chr(ascii('A') + digit - 10);
     else
       hexdigit := to_char(digit);
     end if;
     hexval := hexdigit || hexval;
     N2 := trunc( N2 / 16 );
  end loop;
  return hexval;
END dec2hex;
/

SQL> SELECT dec2hex(44978)  FROM dual;
DEC2HEX(44978)
--------------
AFB2

Also see

  • Binary - numbering system with 2 digits
  • Octal - numbering system with 8 digits
Glossary of Terms
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z #