I'm trying to pull an integer worth of data from /dev/random. The code below works. What I'm trying to understand is why I have to use the size_t type for the final output in order to avoid loss of precision. See the comments in the code.
I thought that perhaps the problem was the .read method adding some type of padding such as a null terminating character, I tried setting the length to 3 to avoid this but it didn't seem to matter. I'm glad a figured out how to resolve this, but I would like to understand why I had to.
size_t getSeed()
{
std::ifstream rnd ("/dev/random", std::ios::binary);
if( rnd.is_open() )
{
int len = sizeof(int); // 4 bytes
char* blk = new char [len];
rnd.read ( blk, len ); // 8 bytes?
rnd.close();
size_t out = (size_t)*blk; // loss of precision with int
delete[] blk;
return out;
}
else
{
return 0;
}
}