Re: converting from dec to hex?

From: Jurij Modic <jurij.modic_at_mf.sigov.mail.si>
Date: 1997/06/20
Message-ID: <33ab0c31.16339572_at_www.sigov.si>#1/1


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

>Does anyone know how to convert from dec. to hex using PL/SQL or perhaps
>without having to write 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

For the first aproximation you can use the function bellow. It converts only non-negative integers. For negative values add your own code - the principle is very similar. You should also add some error handling stuff.

CREATE OR REPLACE FUNCTION dec_to_hex (p_dec IN INTEGER) RETURN VARCHAR2 IS

  v_hex         VARCHAR2(20);  
  v_dec         INTEGER;
  v_remain      INTEGER := p_dec;
  n             INTEGER;
  m             INTEGER;

  FUNCTION single_conv (p_dec INTEGER) RETURN VARCHAR2 IS   BEGIN
    IF p_dec < 10 THEN RETURN TO_CHAR(p_dec);     ELSE RETURN TRANSLATE(TO_CHAR(p_dec-10), '012345', 'ABCDEF');     END IF;
  END single_conv;
BEGIN
  IF p_dec >= 0 THEN
    WHILE v_remain > 16 LOOP
      n := 16;
      m := 0;
      WHILE v_remain >= n LOOP
        n := n*16;
        m := m + 1;
      END LOOP;
      n := n/16;
      v_dec := TRUNC(v_remain/n);
      v_hex := v_hex || single_conv(TO_CHAR(v_dec));
      v_remain := v_remain - v_dec*n;

    END LOOP;
    RETURN v_hex || single_conv(TO_CHAR(v_remain));   ELSE
    RETURN NULL; -- or process negative values   END IF; -- separately - similary as above! END;
/

Regards,


Jurij Modic                             Republic of Slovenia
tel: +386 61 178 55 14                  Ministry of Finance
fax: +386 61  21 45 84                  Zupanciceva 3
e-mail: jurij.modic_at_mf.sigov.mail.si Ljubljana 1000
Received on Fri Jun 20 1997 - 00:00:00 CEST

Original text of this message