Search code examples
c++iobinaryfiles

Converting unsigned int to byte array and back


For a personal project of mine in C++ I've been looking into saving some data in a binary file. I did some research over Google and found several methods of doing this that more or less boiled down to the same thing. However, I cannot for the life of me get either the read or write method to work correctly. Any value I write, I get back differently. I've googled this extensively and looked across StackOverflow and I've not really found the solution so I'm starting to think I must be overlooking something, but I can't for the life of me figure out what.

Below the two methods in question for reading and writing an unsigned short.

unsigned short ReadUShort(std::ifstream& ifs)
{
    unsigned char buffer[2];

    ifs.read((char*)buffer, 2);
    unsigned short val = (buffer[0] << 8) | buffer[1];

    return val;
}

void WriteUShort(std::ofstream& ofs, unsigned short val)
{
    unsigned char buffer[2];

    buffer[0] = (val & 0xff);
    buffer[1] = ((val >> 8) & 0xff);

    ofs.write((char*)buffer, 2);
}

Thank you in advance for any and all help.


Solution

  • You have it reverse. Try this during read:

    unsigned short val = ((unsigned short)buffer[1] << 8) | buffer[0];