To obtain random numbers, this code example uses the dd command to read one byte at a time from /dev/random. Then, it must calculate the numeric equivalent of these numbers. That process is described in “Finding The Ordinal Rank of a Character.”
The following example shows how to read a byte using dd:
# Read four random bytes. |
RAWVAL1=$(dd if=/dev/random bs=1 count=1 2> /dev/null) |
RAWVAL2=$(dd if=/dev/random bs=1 count=1 2> /dev/null) |
RAWVAL3=$(dd if=/dev/random bs=1 count=1 2> /dev/null) |
RAWVAL4=$(dd if=/dev/random bs=1 count=1 2> /dev/null) |
# Calculate the ordinality of the bytes. |
XVAL0=$(ord "$RAWVAL1") # more on this function later |
XVAL1=$(ord "$RAWVAL2") # more on this function later |
YVAL0=$(ord "$RAWVAL3") # more on this function later |
YVAL1=$(ord "$RAWVAL4") # more on this function later |
# We basically want to get an unsigned 16-bit number out of |
# two raw bytes. Earlier, we got the ord() of each byte. |
# Now, we figure out what that unsigned value would be by |
# multiplying the high order byte by 256 and adding the |
# low order byte. We don't really care which byte is which, |
# since they're just random numbers. |
XVAL=$(( ($XVAL0 * 256) + $XVAL1 )) # use expr for older shells. |
YVAL=$(( ($YVAL0 * 256) + $YVAL1 )) # use expr for older shells. |
Last updated: 2008-04-08