Last active
November 6, 2016 18:22
-
-
Save algal/d5615152c2b7db1917253ed3643e26c1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Swift 3, macos/Linux | |
#if os(Linux) | |
import Glibc | |
#else | |
import Darwin | |
#endif | |
class RandomByteGenerator { | |
private let f = fopen("/dev/urandom","r") | |
init() { } | |
deinit { | |
fclose(f) | |
} | |
/// random Int8 | |
func read() -> Int8 { | |
var bytes:[Int8] = [0,0] | |
fgets(&bytes,2,f) | |
bytes.removeLast() | |
return bytes[0] | |
} | |
/// random UInt32 | |
func rand() -> UInt32 | |
{ | |
let a:Int8 = read() | |
let b:Int8 = read() | |
let c:Int8 = read() | |
let d:Int8 = read() | |
let bytes: [Int8] = [a, b,c,d] | |
let u32:UInt32 = UnsafePointer(bytes).withMemoryRebound(to: UInt32.self, capacity: 1) { | |
$0.pointee | |
} | |
return u32 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment