Computer Science 101

with:  Erik Oosterwal

Search for specific programs or algorithms:
Custom Search





Hexadecimal to Decimal


This routine will extract a hexadecimal string from a string array and convert that 4 character string to a decimal integer.  The routine was first written for a data acquisition project I was working on back in the late '80s using a FORTRAN compiler that did not have that function built in.

I'm sure there are more efficient ways of doing the conversion, but this method worked fine for what it was being used for.  TEMP() is a string array that contains formatted information from a Chessell data acquisition device.  The temperature data was returned as a hex value in positions 6 through 9 of the array. The efficiency can probably be improved by accumulating the integer number in the loop rather than storing the value of each hex digit and adding the four values at the end.  Also, some other programming languages allow using a SUBSTITUTION type command that would allow substituting the values 0-15 for the string values 0-9, A-F.  By using substitutions, you would only need one loop instead of two nested loops to convert the string to an integer value.



C     *********************************************************************** 
C 
C     SUBROUTINE TO CHANGE HEX TEMPERATURE VALUE TO DECIMAL VALUE. 
C 
C     ONLY THE 6TH THROUGH THE 9TH CHARACTERS OF THE TEMP ARRAY ARE USED.  
C            THIS SUBROUTINE IS VERY TASK SPECIFIC. 
C 
C     WRITTEN BY:   ERIK P. OOSTERWAL 
C     WRITTEN ON:   NOV. 23, 1987 
C 
C     *********************************************************************** 
      SUBROUTINE HTOD(TEMP,L,ITEMP)
C
      INTEGER*2 IHEX(4),IHEX2(16),L,ITEMP
      CHARACTER*1 IHEX1(16),TEMP(L)
C
      DATA IHEX1/'0','1','2','3','4','5','6','7','8','9',
     *       'A','B','C','D','E','F'/
      DATA IHEX2/0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15/
C
      DO 10,I=6,9
             DO 10,J=1,16
                IF(TEMP(I).EQ.IHEX1(J)) IHEX(I-5)=IHEX2(J)*(16**(9-I))
   10 CONTINUE
C
      ITEMP = IHEX(1)+IHEX(2)+IHEX(3)+IHEX(4)
C
      RETURN
      END


For a more generalized routine that can convert between any two numeric bases, see the Numeric Base Conversion article from the main Computer Science 101 page.





Discuss computer algorithms and other computer science topics at the Computer Algorithms blog page.

All code and original algorithms are © Erik Oosterwal - 1987-2008
Computer Science 101

Dressing for Success