Add checks to not give a result if a thread is not suspended.
[SquirrelJME.git] / utils-dev / random.sh
blob06bdab99439e9a6494931db4fd0c1f2b17db1cfd
1 #!/bin/sh
2 # ---------------------------------------------------------------------------
3 # Multi-Phasic Applications: SquirrelJME
4 # Copyright (C) Stephanie Gawroriski <xer@multiphasicapps.net>
5 # Copyright (C) Multi-Phasic Applications <multiphasicapps.net>
6 # ---------------------------------------------------------------------------
7 # SquirrelJME is under the GNU General Public License v3, or later.
8 # See license.mkd for licensing and copyright information.
9 # ---------------------------------------------------------------------------
10 # DESCRIPTION: Outputs some random bytes as hexadecimal
12 # Force C locale
13 export LC_ALL=C
15 # Directory of this script
16 __exedir="$(dirname -- "$0")"
18 # Need count?
19 if [ "$#" -le "0" ]
20 then
21 echo "Usage: $0 (count)"
22 exit 1
25 # If outputting no bytes, ignore
26 __count="$1"
27 if [ "$__count" -le "0" ]
28 then
29 exit 0
32 # Real random source, if it exists
33 if [ -c /dev/urandom ] || [ -c /dev/random ]
34 then
35 # Unblocked
36 (if [ -c /dev/urandom ]
37 then
38 dd if=/dev/urandom "bs=$__count" count=1
40 # Normal
41 else
42 dd if=/dev/random "bs=$__count" count=1
43 fi) 2> /dev/null | hexdump -x |
44 sed 's/^[0-9a-fA-F]\{1,\}//g' | tr -d ' ' | tr -d '\n' | tr -d '\t'
46 # End with newline
47 echo ""
49 # Not really random, but something
50 else
51 # Seed the random number generator and get a value
52 __seed="$( (echo -n $$ & echo -n $!; date +%s & echo -n $!) |
53 tr -d ' ' | tr -d '\n' | sed 's/[^0-9]*//g' | cut -c 1-8)"
55 # Loop
56 __i=0
57 while [ "$__i" -lt "$__count" ]
59 # Calculate a value
60 __a="$(expr $__seed '*' 1337 | cut -c 1-8)"
62 # Set new seed
63 echo -n "" &
64 __pid="$!"
65 __seed="$__a$__pid"
67 # Add all of the seed values together
68 __rest="$__seed"
69 __xa="0"
70 __xb="1"
71 __j="0"
72 while [ -n "$__rest" ]
74 __char="$(echo "$__rest" | cut -c 1)"
76 # Add to A or B?
77 if [ "$__j" -eq "0" ]
78 then
79 __xa="$(expr "$__xa" + "$__char")"
80 __j="1"
81 else
82 __xb="$(expr "$__xb" + "$__char")"
83 __j="0"
86 # Cut character
87 __rest="$(echo "$__rest" | cut -c 2-)"
88 done
90 # Modulo 16 for hex
91 __ya="$(expr $__xa % 16)"
92 __yb="$(expr $__xb % 16)"
94 # Echo individual hex characters
95 for __q in $__ya $__yb
97 case $__q in
98 10) printf '%s' "a";;
99 11) printf '%s' "b";;
100 12) printf '%s' "c";;
101 13) printf '%s' "d";;
102 14) printf '%s' "e";;
103 15) printf '%s' "f";;
104 *) printf '%s' "$__q";;
105 esac
106 done
108 # Increment
109 __i="$(expr $__i + 1)"
110 done
112 # End with newline
113 echo ""