Binary File Help

Hi, I need help working with binary files in C++

Say for instance there are 4 bytes in a binary file.
0x00 0x00 0x01 0xFF
This is 511 once you convert it from hex to base 10 number.

so let's say I open the file and read it into a char array like this:
1
2
3
4
5
6
7
char dataOffset[4];
    std::ifstream myFile ("myfile.bin", std::ios::in | std::ios::binary);
    if(!myFile)
    {
        //couldn't open do error handling here.
    }
    myFile.read(dataOffset, 4);


So now those 4 bytes should be in the char array myFile. how do i convert them from those 4 bytes to an integer?

How would I convert that integer back to 4 bytes of hex?

Why are types in c/c++ so confusing and hard to work with?
If you are not concerned about endian issues, you can take a shortcut:

1
2
3
4
5
6
7
8
9
// note:  #include <cstdint> for int32_t and related types

int32_t v;
myfile.read( reinterpret_cast<char*>(&v), 4 );

cout << v;  // prints 511 on little endian systems
  // (or -16711680 on big endian systems)

myfile.write( reinterpret_cast<char*>(&v), 4 );


So as you can see: easy but non portable.


If you want the portable version:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// to read:
uint8_t b[4]; // use an unsigned type like uint8_t... don't use char
myfile.read( reinterpret_cast<char*>(b), 4 );

uint32_t v = b[0] |
        (b[1] << 8) |
        (b[2] << 16) |
        (b[3] << 24);

cout << v; // now prints 511 regardless of system endianness

// to write:

b[0] = (v & 0xFF);
b[1] = ((v >> 8) & 0xFF);
b[2] = ((v >> 16) & 0xFF);
b[3] = ((v >> 24) & 0xFF);

myfile.write( reinterpret_cast<char*>(b), 4 );
Thank you.

For the non portable code sample, is it windows only?
Ok, it's not working correctly..

Here are the bytes i'm reading in
0x00 0x00 0x00 0x3C

I used the bottom code sample you gave and cout says the number is:
1006632960
which is
0x3C 0x00 0x00 0x00

It's reading what I want, but it's reversed.
Sorry for triple post, but I fixed it by doing this:

1
2
3
4
uint32_t v = b[0] << 24 |
        (b[1] << 16) |
        (b[2] << 8) |
        (b[3]);


it now reads the correct number which is 60.

Thanks!
Topic archived. No new replies allowed.