[Back To HomePage and Script Library]

Disclaimer: Use these scripts and/or any recommendations they may contain at your own risk. These scripts may or may not have been tested.

Title: Converting Numbers To Hex

This Code of the Week entry comes from Vimal Nair, a consultant, for BEST Consulting
      in Kirkland, Washington.

      I use this function to convert numbers to hexadecimals.
Source/Text/Comments


      CREATE OR REPLACE FUNCTION NUMTOHEX(v_dec  NUMBER )

      RETURN VARCHAR2 IS

        val NUMBER;

        v_hex_mod VARCHAR2(1);

        v_hex_val VARCHAR2(1);

        v_hex    VARCHAR2(20);

        v_mod varchar2(25);

      BEGIN

       val := v_dec;

       if v_dec > 15 then

           while  val > 15 loop

               select decode(to_char(mod(val,16)),'10','A','11','B','12',

               'C','13','D','14','E','15','F',to_char(mod(val,16)))

                INTO v_hex_mod from dual;

                       v_mod := v_hex_mod||v_mod;

                       val := trunc(val/16);

       end loop;

          select decode(to_char(val),'10','A','11','B','12','C',

          '13','D','14','E','15','F',to_char(val)) INTO v_hex_val from dual;

             v_hex := nvl(v_hex_val,'0')||nvl(v_mod,'0');

               RETURN(NVL(v_hex,'0'));

      else

            select decode(to_char(v_dec),'10','A','11','B','12','C','13',

            'D','14','E','15','F',to_char(v_dec)) INTO v_hex from dual;

              RETURN('0'||NVL(v_hex,'0'));
      end if;

      END NUMTOHEX;
      /