开发者

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

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 inte开发者_开发技巧ger types will be of widths specified? What is the best way to achieve this?


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.


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜