If you need to enforce how many bits are in an integer type, you need to be using the <stdint.h>
header. It is present in both C and C++. It defines type such as uint8_t
(8-bit unsigned integer), which are guaranteed to resolve to the proper type on the platform. It also tells other programmers who read your code that the number of bits is important.
If you're worrying about performance, you might want to use the larger-than-8-bits types, such as uint32_t
. However, when reading and writing files, you will need to pay attention to the endianess of your system. Notably, if you have a little-endian system (e.g. x86, most all ARM), then the 32-bit value 0x12345678
will be written to the file as the four bytes 0x78 0x56 0x34 0x12
, while if you have a big-endian system (e.g. Sparc, PowerPC, Cell, some ARM, and the Internet), it will be written as 0x12 0x34 0x56 0x78
. (same goes or reading). You can, of course, work with 8-bit types and avoid this issue entirely.