How to Convert a Base Number to Its Decimal Equivalent

ID: Q98749

The information in this article applies to:

The follwing sample program (TEST.PRG) demonstrates how to use the CONVERT() function in a program. The CONVERT() function converts a number to its decimal equivalent depending on the base specified. The function accepts two parameters: the number to be converted, and the base to convert from.

* PROGRAM TEST.PRG

   CLEAR
   SET TALK OFF

   Hex_Number=SPACE(4)
   Base1=0
   Dec_Number=0
   @ 3,5 SAY "Program to Convert Any Base to a Decimal Number"
   @ 5,5 SAY "Enter the Number " GET Hex_Number PICTURE "@K!!"
   @ 7,5 SAY" Enter the Base " Get base1 PICTURE "@K!!"

   READ

   * CONVERT Function being called
   Dec_Number=CONVERT(Hex_Number,Base1)

   * Print the value number returned

   ? Dec_Number

   * Start of FUNCTION CONVERT

   FUNCTION CONVERT
   * Parameter to be passed
   PARAMETER Number,Base
   PUBLIC Digit
   DIMENSION Digit(16)
   Power=0
   Answer=0

   * If the parameter being passed is less than four, add zeros in
   * front of the number

   IF LEN(ALLTRIM(Number)) < 4
      Number=PADL(ALLTRIM(Number),4,'0')
   ENDIF

   Digit[16]="0123456789ABCDEF"

   FOR X = 15 TO 1 STEP -1
     Digit[X] = SUBSTR(Digit[16],1,X)
   ENDFOR

   FOR X=LEN(Number) TO 1 STEP -1
     Answer=Answer+(Base^Power)*(AT(SUBSTR(Number,X,1),Digit[Base])-1)
     Power = Power + 1
   ENDFOR

   RETURN (Answer)

Additional reference words: FoxDos FoxWin 2.50 2.00 2.50a KBCategory: kbprg kbcode KBSubcategory: FxprgGeneral

Last Reviewed: June 27, 1995