I have a struct with three variables: two unsigned ints and an unsigned char. From my understanding, a c++ char is always 1 byte regardless of what operating system it is on. The same can’t be said for other datatypes. I am looking for a way to normalize POD’s so that when saved into a binary file, the resulting file is readable on any operating system that the code is compiled for.
I changed my struct to use a 1-byte alignment by adding #pragma as follows:
#pragma pack(push, 1)
struct test
{
int a;
}
#pragma pack(pop)
but that doesn’t necessarily mean that int a is exactly 4 bytes on every os, I don’t think? Is there a way to ensure that a file saved from my code will always be readable?
You can find fixed-width integer types (like
std::int32_tandstd::uint16_t) in<cstdint>. Your C++ Standard Library implementation may not include<cstdint>(it’s not part of the current C++ standard; it’s part of C++0x), in which case Boost has an implementation that should work on most platforms.Note that you will still have to think about endianness and alignment, among other things. If your code needs to run on platforms with different numeric representations (e.g. one’s complement and two’s complement), you’ll need to consider that too.