Apple Developer Connection
Member Login Log In | Not a Member? Contact ADC

< Previous PageNext Page > Hide TOC

Obtaining Random Numbers

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.


< Previous PageNext Page > Hide TOC


Last updated: 2008-04-08




Did this document help you?
Yes: Tell us what works for you.

It’s good, but: Report typos, inaccuracies, and so forth.

It wasn’t helpful: Tell us what would have helped.
Get information on Apple products.
Visit the Apple Store online or at retail locations.
1-800-MY-APPLE

Copyright © 2007 Apple Inc.
All rights reserved. | Terms of use | Privacy Notice