2

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.

2 Answers 2

2

Your read routine reads in big-endian order (most-significant byte first), and your write routine writes in little-endian order (least-significant byte first). You'll have to choose one or the other.

A big endian implementation:

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];

    //SWAPPED FROM LITTLE-ENDIAN TO BIG-ENDIAN
    buffer[0] = ((val >> 8) & 0xff); 
    buffer[1] = (val & 0xff);

    ofs.write((char*)buffer, 2);
}
Sign up to request clarification or add additional context in comments.

2 Comments

slaps himself I can't believe I kept overlooking that.
I'd mark two correct answers if I could, as you're as correct as the poster above.
1

You have it reverse. Try this during read:

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

1 Comment

@RenegadeVile glad if this helped.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.