Cross-platform primitive data types in C++

前端 未结 7 2455
鱼传尺愫
鱼传尺愫 2021-02-14 07:04

Unlike Java or C#, primitive data types in C++ can vary in size depending on the platform. For example, int is not guaranteed to be a 32-bit integer. Various compi

相关标签:
7条回答
  • 2021-02-14 07:15

    Part of the C99 standard was a stdint.h header file to provide this kind of information. For instance, it defines a type called uint32_t. Unfortunately, a lot of compilers don't support stdint.h. The best cross-platform implementation I've seen of stdint.h is here: http://www.azillionmonkeys.com/qed/pstdint.h. You can just include that in your project.

    If you're using boost, I believe it also provides something equivalent to the stdint header.

    0 讨论(0)
  • 2021-02-14 07:22

    Two things:

    First, there is a header file called limits.h that gives lots of useful platform specific information. It will give max and min values for the int type for example. From that, you can deduce how big the int type is.

    You can also use the sizeof operator at runtime for these purposes too.

    I hope this helps . . .

    K

    0 讨论(0)
  • 2021-02-14 07:22

    There is a stdint.h header defined by the C99 standard and (I think) some variant or another of ISO C++. This defines nice types like int16_t, uint64_t, etc... which are guaranteed to have a specific size and representation. Unfortunately, it's availability isn't exactly standard (Microsoft in particular was a foot dragger here).

    The simple answer is this, which works on every 32 or 64 bit byte-addressable architecture I am aware of:

    • All char variables are 1 byte
    • All short variables are 2 bytes
    • All int variables are 4 byte
    • DO NOT use a "long", which is of indeterminate size.
    • All known compilers with support for 64 bit math allow "long long" as a native 64 bit type.

    Be aware that some 32 bit compilers don't have a 64 bit type at all, so using long long will limit you to 64 bit systems and a smaller set of compilers (which includes gcc and MSVC, so most people won't care about this problem).

    0 讨论(0)
  • 2021-02-14 07:25

    Define a type (e.g. int32) in a header file. For each platform use another #ifdef and make sure that in32 is a 32 bit integer. Everywhere in your code use int32 and make sure that when you compile on different platforms you use the right define

    0 讨论(0)
  • 2021-02-14 07:30

    If its name begins with two underscores (__), a data type is non-standard.

    __int8 (unsigned __int8)

    __int16 (unsigned __int16)

    __int32 (unsigned __int32)

    __int64 (unsigned __int64)

    Try to use boost/cstdint.hpp

    0 讨论(0)
  • 2021-02-14 07:31

    I found this header particularly useful: BOOST cstdint

    Usually better than inventing own wheel (which incurs the maintenance and testing).

    0 讨论(0)
提交回复
热议问题