Search code examples
c++intarrays

4 chars to int in c++


I have to read 10 bytes from a file and the last 4 bytes are an unsigned integer. But I got a 11 char byte long char array / pointer. How do I convert the last 4 bytes (without the zero terminating character at the end) to an unsigned integer?

//pesudo code
char *p = readBytesFromFile();
unsigned int myInt = 0;
for( int i = 6; i < 10; i++ )
    myInt += (int)p[i];

Is that correct? Doesn't seem correct to me.


Solution

  • The following code might work:

    myInt = *(reinterpret_cast<unsigned int*>(p + 6));
    

    iff:

    • There are no alignment problems (e.g. on a GPU memory space this is very likely to blow if some guarantees aren't provided).
    • You can guarantee that the system endianness is the same used to store the data
    • You can be sure that sizeof(int) == 4, this is not guaranteed everywhere

    If not, as Dietmar suggested, you should loop over your data (forward or reverse according to the endianness) and do something like

    myInt = myInt << 8 | static_cast<unsigned char>(p[i])
    

    this is alignment-safe (it should be on every system). Still pay attention to points 1 and 3.