Fixed-width integers in ANSI C
Asked Answered
H

2

2
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.

Holliman answered 24/7, 2012 at 12:48 Comment(0)
A
2

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.

Ascomycete answered 24/7, 2012 at 13:5 Comment(2)
and what if there is no type 32-bit large?Holliman
long has a minimum size of 32 bits under C89, and its the largest type. If there's no long, your probably have big issues, in which you'll have to manually piece together 16 bit or 8 bit integers. Its doable, just annoying. You can typedef or create a struct of bytes to make up your type. https://mcmap.net/q/109409/-typedef-fixed-length-array But in C89, there should be a long type.Ascomycete
C
0

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.

Copper answered 14/9, 2012 at 16:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.