I have a variable of type uint8_t
which I'd like to serialize and write to a file (which should be quite portable, at least for Windows, which is what I'm aiming at).
Trying to write it to a file in its binary form, I came accross this working snippet:
uint8_t m_num = 3;
unsigned int s = (unsigned int)(m_num & 0xFF);
file.write((wchar_t*)&s, 1); // file = std::wofstream
First, let me make sure I understand what this snippet does - it takes my var (which is basically an unsigned char, 1 byte long), converts it into an unsigned int
(which is 4 bytes long, and not so portable), and using & 0xFF
"extracts" only the least significant byte.
Now, there are two things I don't understand:
- Why convert it into
unsigned int
in the first place, why can't I simply do something like
file.write((wchar_t*)&m_num, 1);
orreinterpret_cast<wchar_t *>(&m_num)
? (Ref) - How would I serialize a longer type, say a
uint64_t
(which is 8 bytes long)?unsigned int
may or may not be enough here.