When working with different numeric bases, such as binary or hexadecimal, converting between numbers and strings is a common task. With 4D 21, the String and Num commands have been enhanced to make these conversions more powerful.
Convert a number to a string in any base
The String command now supports conversion from an integer to a string in any base from 2 to 36. This makes it simple to represent values in binary, octal, decimal, hexadecimal, and beyond.
var $result := String(6; 2)
// "110" — binary representation of 6
$result := String(254; 16)
// "fe" — hexadecimal representation of 254
$result := String(14256; 36)
// "b00" — base 36 representation of 14256
Convert a string to an integer
The Num command now also supports parsing strings in any base from 2 to 36. This is especially helpful when working with hexadecimal or binary inputs.
var $result:=Num("110";2)
// $result = 6
$result:=Num("fe";16)
// $result = 254
$result:=Num("b00";36)
// $result = 14256
Note: Since Num uses the historical 4D algorithm when no base is specified, and the ECMAScript algorithm when a base is provided, you might notice differences with very large numbers like 1e+25 and beyond.
Conclusion
Whether you’re building a developer tool, debugging protocols, or just displaying numbers in a more readable format, these enhancements offer more flexibility and control. Now you can easily switch between numeric bases, validate user input, or serialize data in formats like hexadecimal or binary natively in 4D.
