KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Converting Number Bases
PRODUCT: 4D | VERSION: 14.x | PLATFORM: Mac & Win
Published On: February 26, 2016

Below is a utility method to convert a Base 10 number to another Unit base number in a text format by passing in the value and the desired resulted base:

// Util_Base10Convert
//
// Desription:
// Converts numeric base 10 value to another
// base number displayed in Text format
//
// Parameters:
// $1: Input Value
// $2: Base of result
// Results:
// $0: Resulting Converted Number in text format
// ----------------------------------------------------

C_LONGINT($1;$value_l)
C_LONGINT($2;$base_l)
C_TEXT($0;$result_t)

If (Count parameters=2)
    C_LONGINT($remainder_l)
    $value_l:=$1
    $base_l:=$2
   
    While ($value_l>0)
       $remainder_l:=$value_l%$base_l
       If ($remainder_l>9)
          $result_t:=Char($remainder_l+55)
       Else
          $result_t:=String($value_l%$base_l)+$result_t
       End if
       $value_l:=$value_l\$base_l
    End while
    $0:=$result_t
   
End if


Below is a utility method to convert back to a Base 10 number from a Text format number in another Base value:
// Util_Base10Revert
//
// Desription:
// Converts text base value to a base 10 number
//
// Parameters:
// $1: Input Value
// $2: Base of Input
// Results:
// $0: Resulting Converted Number
// ----------------------------------------------------

C_TEXT($1;$value_t)
C_LONGINT($2;$base_l)
C_LONGINT($0;$result_l)

If (Count parameters=2)
    C_LONGINT($length_l;$i)
    C_TEXT($char_t)
    $value_t:=$1
    $base_l:=$2
   
    $length_l:=Length($value_t)
    For ($i;1;$length_l)
       $char_t:=Substring($value_t;$i;1)
       If (Character code($char_t)<65)
          $result_l:=($result_l*$base_l)+(Num($char_t))
       Else
          $result_l:=($result_l*$base_l)+Character code($char_t)-55
       End if
    End for
    $0:=$result_l
End if

Notes:
  • Both of these methods only go up to base 36, due to limits in the uppercase letter alphabet.

  • The Util_Base10Revert method does not check whether or not the passed value is a valid number for the passed base, ie FF for a base 8 value.


Example of using the commands:
C_TEXT($out1;out2;out3)

$out1:=(1234;8) //$out1="2322"
$out2:=(1234;18) //$out2="3EA"
$out3:=(1234;28) //$out3="1G2"

C_LONGINT($out4;$out5;$out6)

$out4:=("12YZ";36) //$out4=50507
$out5:=("12MN";26) //$out5=19523
$out6:=("12EF";16) //$out6=4847