Created
March 24, 2014 17:30
-
-
Save mortenpi/9745042 to your computer and use it in GitHub Desktop.
Short generic C++ function to read random data of any type from /dev/urandom.
This file contains 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
#include <fstream> | |
#include <cstdlib> | |
template<class T> | |
T read_urandom() | |
{ | |
union { | |
T value; | |
char cs[sizeof(T)]; | |
} u; | |
std::ifstream rfin("/dev/urandom"); | |
rfin.read(u.cs, sizeof(u.cs)); | |
rfin.close(); | |
return u.value; | |
} |
This file contains 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
#include <fstream> | |
#include <cstdlib> | |
template<class T> | |
T read_urandom() | |
{ | |
union { | |
T value; | |
char cs[sizeof(T)]; | |
} u; | |
std::ifstream rfin("/dev/urandom"); | |
rfin.read(u.cs, sizeof(u.cs)); | |
rfin.close(); | |
return u.value; | |
} | |
#include <iostream> | |
using namespace std; | |
int main(int argc, char * argv[]) | |
{ | |
cout << read_urandom<short>() << endl; | |
cout << read_urandom<int>() << endl; | |
cout << read_urandom<long>() << endl; | |
cout << (unsigned int)read_urandom<unsigned char>() << endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment