I'm trying to read an unsigned long
number from a binary file.
i'm doing this in this way:
infile.open("file.bin", std::ios::in | std::ios::binary);
char* U=new char[sizeof(unsigned long)];
unsigned long out=0;
infile.read(U, sizeof(unsigned long));
out=static_cast<unsigned long>(*U);
delete[] U;
U=NULL;
infile.close();
but result is not correct.
My data is 6A F2 6B 58 00 00 00 00
witch should be read as 1483469418
but out is 106
in my code which is just the first byte of data
What is the problem?
how should i correctly read an unsigned long
from file?
That is because you are casting a dereferenced value. I.e. only a char
not full 4 bytes. *U
is 106
.
You can read the data in without the intermediate buffer:
infile.read(reinterpret_cast<char*>(&out), sizeof out);
The difference is that here you are reinterpreting the pointer, not the value under it.
If you still want to use the buffer, it should be *reinterpret_cast<unsigned long*>(U);
, this also reinterprets the pointer 1st, and then dereferences it. The key is to dereference a pointer of proper type. The type of pointer determines how many bytes are used for the value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With