read unsigned long from binary file

1.7k Views Asked by At

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?

4

There are 4 best solutions below

3
On BEST ANSWER

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.

0
On

Try out=*reinterpret_cast<unsigned long *>(U);

0
On

out=static_cast(U); should be out=(unsigned long *)(U);

It can be much simpler:

infile.open("file.bin", std::ios::in | std::ios::binary);
unsigned long out=0;
infile.read((char *)&out, sizeof(out));
infile.close();
4
On

You need to know whether the file (not the program) is big endian or little endian. Then read the bytes with fgetc() and reconsitute the number

so

  unsigned long read32be(FILE *fp)
  {
      unsigned long ch0, ch1, ch2 ch3;

      ch0 = fgetc(fp);
      ch1 = fgetc(fp);
      ch2 = fgetc(fp);
      ch3 = fgetc(fp);

      return (unsigned long) (ch0 << 24) | (ch1 << 16) | (ch2 << 8) | ch3
  }

Now it will work regardless of whether longs is 32 bits or 64, big_endian or little endian. If the file is little endian, swap the order of the fgetc()s.

Reading binary files portably is surprisingly tricky. I've put some code on github

https://github.com/MalcolmMcLean/ieee754