Exact-width integer types in C (stdint.h)

2019-02-24 20:45发布

问题:

I would like char, short and int types to be 1, 2 and 4 bytes width. I have included a stdint.h header into my sources. Does this guarantee that int8_t, int16_t and int32_t integer types will be of widths specified? What is the best way to achieve this?

回答1:

If these types exist, they have the correct width and are encoded in two's complement.

Edit: you should be able to check if the types exist with something like

#ifdef INT32_MAX
...
#endif

but on all end user architectures (PC etc) these types do usually exist.



回答2:

The whole purpose of the types defined in stdint.h is of them to be of specified width. So int8_t will be 8 bits wide, int16_t - 16 bits wide, etc.



回答3:

stdint.h some exact-width integer types. These are (from wikipedia):

Specifier   Signing      Bits   Bytes   
int8_t        Signed       8       1    
uint8_t       Unsigned     8       1    
int16_t       Signed       16      2    
uint16_t      Unsigned     16      2    
int32_t       Signed       32      4    
uint32_t      Unsigned     32      4    
int64_t       Signed       64      8 
uint64_t      Unsigned     64      8    

Use them if you want to know what the size is for definite. C99 requires that these types have the sizes specified. All other types are platform dependent.

Other types are guaranteed to be a certain minimum width, as per limits.h. But they could equally be bigger than that. It is up to the implementation.



回答4:

C99's stdint.h does not actually guarantee that these types exist. To quote wikipedia:

These types are optional unless the implementation supports types with widths of 8, 16, 32 or 64, then it shall typedef them to the corresponding types with corresponding N.

However, if they do exist, they will be the correct widths.



回答5:

You can check: Size of int in C on different architectures



标签: c integer size