Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read unsigned long from binary file

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?

like image 765
Ariyan Avatar asked Dec 23 '22 22:12

Ariyan


1 Answers

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.

like image 151
luk32 Avatar answered Jan 05 '23 16:01

luk32