Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing unsigned int to binary file

Tags:

c++

My first time working with binary files and I'm having clumps of hair in my hands. Anyway, I have the following defined:

unsigned int cols, rows;

Those variables can be anywhere from 1 to about 500. When I get to writing them to a binary file, I'm doing this:

    myFile.write(reinterpret_cast<const char *>(&cols), sizeof(cols));
    myFile.write(reinterpret_cast<const char *>(&rows), sizeof(rows));

When I go back to read the file, on cols = 300, I get this as result:

44
1
0
0

Can someone please explain to me why I'm getting that result? I can't say that there's something wrong, as I honestly think it's me who don't understand things. What I'd LIKE to do is store the value, as is, in the file so that when I read it back, I get that as well. And maybe I do, I just don't know it.

I'd like some explanation of how this is working and how do I get the data I put in read back.

like image 991
KirAsh4 Avatar asked Mar 23 '23 14:03

KirAsh4


2 Answers

You are simply looking at the four bytes of a 32 bit integer, interpreted on a little-endian platform.

300 base 10 = 0x12C

So little-endianness gives you 0x2C 0x01, and of course 0x2C=44.

like image 144
huskerchad Avatar answered Mar 26 '23 04:03

huskerchad


Each byte in the file has 8 bits, so can represent values from 0 to 255. It's written in little-endian order, with the low byte first. So, starting at the other end, treat the numbers as digits in base 256. The value is 0 * 256^3 + 0 * 256^2 + 1 * 256^1 + 44 * 256^0 (where ^ means exponentiation, not xor).

like image 39
Pete Becker Avatar answered Mar 26 '23 05:03

Pete Becker