Tech Tip: Random numbers above 32,767
PRODUCT: 4D | VERSION: 16 | PLATFORM: Mac & Win
Published On: May 15, 2017
The Random command gives you a 15bit random integer value between 1 and 32,767 inclusive.
To get a larger value, such as a 30bit integer value, we can combine several 15 bit values like this:
$vlResult:=(((Random << 15)+Random) |
This syntax can be combined with the start/stop syntax for specifying the start and stop numbers :
$vlResult:=(((Random << 15)+Random)%($vlEnd-$vlStart+1))+$vlStart |
Here is a utility method that can return a random number up to the max longint value:
// $rand:=UTIL_Random(50000;100000) C_LONGINT($0;$vlResult) C_LONGINT($1;$vlStart) C_LONGINT($2;$vlEnd) If (Count parameters=2) $vlStart:=$1 $vlEnd:=$2 $vlResult:=(((Random << 15)+Random)%($vlEnd-$vlStart+1))+$vlStart $0:=$vlResult End if |
If the above method is saved as UTIL_Random then it could be used like this:
C_LONGINT($vlResult;$vlEnd;$vlStart) $vlEnd:=2000000000 $vlStart:=1990000000 $vlResult:=UTIL_Random($vlStart;$vlEnd) ALERT(String($vlResult;"###,###,###,##0")) |
The sample code above will produce a random number between 1,990,000,000 and 2,000,000,000