简体   繁体   中英

Will int32 be the same size on all platforms?

I'm developing a multi platform app (iOS, Android, etc), using C++.

Are there base types in the C++ standard which are guaranteed to be a fixed width, and portable across multiple platforms?

I'm looking for fixed-width types such as Int32, UInt32, Int16, UInt16, Float32, etc.

int32 is a custom typedef, only int exists by default. If you need a specified width take a look at stdint.h

#include <cstdint>

int32_t integer32bits;

I don't think any floating point counterpart exists in the standard, correct me if I'm wrong.

Floats are almost always 32 bit except on some obscure platforms that do not comply with IEEE 754. You don't need to bother with those, in all likelihood. Integer types may vary, but if your target platform has a C++11-compliant compiler, then you can use the cstdint header to access types of a specific size in a standard way. If you can't use C++11, then you will need separate code for each platform, most likely.

The definitions in <stdint.h> , or <cstdint> can be used for portability:

  • int32_t is guaranteed to be a typedef for a signed 32 bit type, or not exist at all. Since this is C++, you can use enable_if to decide on a course of action.
  • int_least32_t is a typedef for the smallest type that has at least 32 bits
  • int_fast32_t is a typedef for a type that has at least 32 bit and can be operated on efficiently (eg if the memory bus is 64 bit wide and allows no partial stores, it is faster to use a 64 bit type and waste memory rather than perform read-modify-write accesses)

See also The difference of int8_t, int_least8_t and int_fast8_t .

Note that different systems can also have different endianness, so it is never safe to transmit these over the network.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM