问题
How do I handle a 4-byte char array as a typical int in ANSI C?
Some context:
I'm parsing a binary file, where I need to read 4-bytes unsigned integers.
I want to make sure that, no matter what platform this parser is compiled in, an "int" is always 4 bytes long.
I've read about uint32_t & friends, but I'm limited to ANSI C.
Thanks in advance.
回答1:
throw some preprocessor commands in there
#include <limits.h>
#if LONG_BIT == 32
long buffer [BUFFER_SIZE];
#elif WORD_BIT == 32
int buffer [BUFFER_SIZE];
#endif
you also could use sizeof(int) during runtime.
回答2:
I would suggest that rather than trying to overlay data, you may be better off simply writing functions to do things like uint32 GetUInt32LE(unsigned char *dat)
, which could then be implemented as return ((uint32)(dat[3]) << 24) | ((uint32)(dat[2]) << 16) | ((uint32)(dat[1]) << 8) | dat[0];
for maximal portability (assuming one has defined uint32
suitably), or could be defined somewhat more simply on systems where a int
was known to be 32 bits or larger. Note that there are still some embedded compilers for smaller systems where int
is only 16 bits, so the casts on the individual bytes are needed. The cast on dat[1]
is needed on such systems because otherwise shifting a byte value like 0xFF left by eight would otherwise yield undefined behavior whose most probable actual result would be to interpret it as (int)(0xFF00), which would be sign-extended to 0xFFFFFF00, clobbering the two upper bytes of the result.
来源:https://stackoverflow.com/questions/11631206/fixed-width-integers-in-ansi-c