Skip to content

Instantly share code, notes, and snippets.

@mortenpi
Created March 24, 2014 17:30
Show Gist options
  • Save mortenpi/9745042 to your computer and use it in GitHub Desktop.
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.
#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 <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