Consultor Eletrônico



Kbase 18951: How To Convert Hexadecimal Values To Decimal
Autor   Progress Software Corporation - Progress
Acesso   Público
Publicação   15/10/2008
Status: Verified

GOAL:

How to convert HEXADECIMAL values to DECIMAL with a procedure

FACT(s) (Environment):

Progress 7.x
Progress 8.x
Progress 9.x

FIX:

This procedure will take any length hexadecimal number and convert it to an integer.

DEFINE VARIABLE h AS CHARACTER NO-UNDO.
DEFINE VARIABLE d AS INTEGER NO-UNDO.

REPEAT:
UPDATE h.
 RUN HexToDec(INPUT h, OUTPUT d).
 DISPLAY d.
END.

PROCEDURE HexToDec:
DEFINE INPUT PARAMETER v-hex AS CHARACTER NO-UNDO.
  DEFINE OUTPUT PARAMETER v-num AS INTEGER NO-UNDO INITIAL 0.

  DEFINE VARIABLE i AS INTEGER NO-UNDO.

   ASSIGN v-hex = CAPS(v-hex).

  /* hexadecimal should always be capitals, but... */
  /* review each char and evaluate if it is an integer or letter. */
   /* If it is a letter determine its value and add 10. */
   /* Then multiply the char value times 16 to the char position */
/* minus 1. EXAMPLE: v-hex = 1180C */
   /*     Char 1 - 1 * 16 to the 4th (5 - 1) power = 65536 */
   /*     Char 2 - 1 * 16 to the 3rd (5 - 2) power = 4096 */
   /*     Char 3 - 8 * 16 to the 2nd (5 - 3) power = 2048 */
   /*     Char 4 - 0 * 16 to the 1st (5 - 4) power = 0 */
   /*     Char 5 - C or 2 + 10 * 10 to 0 power = 12 */
   /*     integer value is 71692 */

DO i = 1 TO LENGTH(v-hex):
    IF CAN-DO("0,1,2,3,4,5,6,7,8,9", (SUBSTRING(v-hex, i, 1))) THEN
         ASSIGN v-num = v-num + INTEGER(SUBSTRING(v-hex, i, 1)) * EXP(16, (LENGTH(v-hex) - i)).
     ELSE
         ASSIGN v-num = v-num + (KEYCODE(SUBSTRING(v-hex, i, 1)) - KEYCODE("A") + 10) * EXP(16, (LENGTH(v-hex) - i)).
   END.
END PROCEDURE.