Tech Tip: Converting Hexadecimal to Decimal in native 4D code
PRODUCT: 4D | VERSION: 15.3 | PLATFORM: Mac & Win
Published On: October 28, 2016
The following method converts a hexadecimal (string) to a decimal (long integer) value using native 4D code:
If the code above is saved as UTIL_HEXTODEC it could be used like this to convert the hexadecaimal value of "4D" to the decimal value of 77:
In the following example the UTIL_HEXTODEC project method is used to convert the hexadecimal value of DECAF to the decimal value of 912,559
The limitation of this project method is 7FFFFFFF or 2,147,483,647 which is the max value for a signed long integer.
If this project method were used to convert a hexadecimal value larger than 7FFFFFFFF the returned value will be incorrect due to overflow; for example, the hexadecimal value of 80000000 converts to -2,147,483,648
// ---------------------------------------------------- // Method: UTIL_HEXTODEC // Example: $var_longint:=UTIL_HEXTODEC($var_hex_text) // Description: Converts a hexadecimal string ("4D") to a longint (77) // Parameters: // $0 := Long Int // $1 := Text // ---------------------------------------------------- C_LONGINT($0;$location;$length;$total;$a;$thisValue) C_TEXT($1;$hex) If (Count parameters=1) $hex:=$1 $length:=Length($hex) $total:=0 For ($a;1;$length) Case of : ($hex[[$a]]="A") $thisValue:=10 : ($hex[[$a]]="B") $thisValue:=11 : ($hex[[$a]]="C") $thisValue:=12 : ($hex[[$a]]="D") $thisValue:=13 : ($hex[[$a]]="E") $thisValue:=14 : ($hex[[$a]]="F") $thisValue:=15 Else $thisValue:=Num($hex[[$a]]) End case $location:=$length-$a $total:=$total+($thisValue*(16^$location)) End for End if $0:=$total |
If the code above is saved as UTIL_HEXTODEC it could be used like this to convert the hexadecaimal value of "4D" to the decimal value of 77:
ALERT(String(UTIL_HEXTODEC ("4D"))) // 77 |
In the following example the UTIL_HEXTODEC project method is used to convert the hexadecimal value of DECAF to the decimal value of 912,559
ALERT(String(UTIL_HEXTODEC ("DECAF"))) // 912559 |
The limitation of this project method is 7FFFFFFF or 2,147,483,647 which is the max value for a signed long integer.
If this project method were used to convert a hexadecimal value larger than 7FFFFFFFF the returned value will be incorrect due to overflow; for example, the hexadecimal value of 80000000 converts to -2,147,483,648