Converting a number to Hexidecimal and back

Chris Kelleher

Administrator
Staff member
> Does anyone have a routine that could take a number like 6850469
> and convert it to hexidecimal?

OldBase returns the decimal equivalent, NewBase returns the number
in any arbitrary base up to 36.

<BLOCKQUOTE><font size="1" face="Arial, Verdana">code:</font><HR><pre>
FUNCTION OldBase RETURNS DECIMAL (ip_cNumber AS CHARACTER,ip_iBase AS INTEGER):
DEFINE VARIABLE lNegative AS LOGICAL NO-UNDO.
DEFINE VARIABLE nResult AS DECIMAL DECIMALS 0 NO-UNDO.
DEFINE VARIABLE iLoop AS INTEGER NO-UNDO.
DEFINE VARIABLE iDigit AS INTEGER NO-UNDO.
IF ip_cNumber = ? OR ip_cNumber = "?":u THEN RETURN ?.
lNegative = INDEX(ip_cNumber,"-":u) > 0.
DO iLoop = 1 TO LENGTH(ip_cNumber):
iDigit = ASC(CAPS(SUBSTRING(ip_cNumber,iLoop,1))).
IF iDigit < 48 OR (iDigit > 57 AND iDigit < 65 OR iDigit > 90) THEN NEXT.
ASSIGN
iDigit = iDigit - (IF iDigit < 65 THEN 48 ELSE 55)
nResult = nResult * DECIMAL(ip_iBase) + iDigit.
END.
RETURN (IF lNegative THEN - nResult ELSE nResult).
END FUNCTION.


FUNCTION NewBase RETURNS CHARACTER (ip_nNumber AS DECIMAL,ip_iBase AS INTEGER):
DEFINE VARIABLE cResult AS CHARACTER NO-UNDO.
DEFINE VARIABLE iDigit AS INTEGER NO-UNDO.
DEFINE VARIABLE lNegative AS LOGICAL NO-UNDO.
/* Take the remainder to find the value of the current position. */
/* If the result is less than ten, return a digit (0..9). */
/* Otherwise, return a letter (A..Z). */
IF ip_iBase < 2 OR ip_iBase > 36 OR ip_iBase = ? OR ip_nNumber = ? THEN
RETURN ?.
ASSIGN
cResult = ""
lNegative = ip_nNumber < 0
ip_nNumber = ABSOLUTE(ip_nNumber).
DO WHILE ip_nNumber > 0:
ASSIGN
iDigit = ip_nNumber - TRUNCATE(ip_nNumber / ip_iBase,0) * ip_iBase
cResult = CHR(iDigit + IF iDigit < 10 THEN 48 ELSE 55)
+ cResult
ip_nNumber = TRUNCATE(ip_nNumber / ip_iBase,0).
END.
RETURN (IF lNegative THEN "-":u ELSE "")
+ (IF cResult = "" THEN "0":u ELSE cResult).
END FUNCTION.
[/code]
 
Top