Fixed-width integers in C++

后端 未结 6 1984
梦谈多话
梦谈多话 2020-12-10 01:59

Occasionally I need to use fixed-width integers for communication with external devices like PLCs. I also use them to define bitmasks and perform bit manipulation of image d

相关标签:
6条回答
  • 2020-12-10 02:11

    There are different paths to take. Most environments would hold that short ints are 16 bits, and long ints are 32. (The long is implied when you declare simply int.) If you typedef your own int16 type, you'll probably end up using a short int.

    Another possibility lies with bit fields in structs. You can say something like:

    struct x {
        int a : 16;
        int b : 5;
        ...
    };
    

    And so forth. If you then define:

    struct x myvar;
    myvar.a = 54;
    

    You can be sure that myvar.a will hold 16 bits, and myvar.b will use 5; the total size of myvar rounding up for what all the bits comprise, plus of course the size of any other fields.

    0 讨论(0)
  • 2020-12-10 02:19

    Include the file <stdint.h> to get the definitions for types like uint16_t. VC++ doesn't come with <stdint.h> by default, but you can get that file from several places. Wikipedia lists a few, and Google will find you lots more.

    0 讨论(0)
  • 2020-12-10 02:21

    Will the next C++ standard define fixed-width integers?

    Yes.

    As Mehrdad said, you can use #ifdefs for now. An alternative would be some elaborate template magic. Boost has got something in this direction, the Boost Integer library.

    0 讨论(0)
  • 2020-12-10 02:23

    You can workaround the problem with some #ifdef directives.

    #ifdef _MSC_VER
       typedef __int16 int16_t
    #else
       #include <stdint.h>
    #endif
    
    0 讨论(0)
  • 2020-12-10 02:25

    Boost has the typedefs for all of the C99 types and more: "Boost integer library"

    0 讨论(0)
  • 2020-12-10 02:30

    I've used a public domain (not GPL - true public domain) version of stdint.h by Danny Smith that's available in the mingw package:

    • http://www.mingw.org/download.shtml

    I had to tweak that version to compile with some non VC 8 compilers (mostly VC6) - it has served me well.

    Maybe one of these days I'll get around to posting my VC6-compatible version somewhere. The changes were pretty minor - just some macro trickery to use VC6 specific keywords for 64-bit types. If you don't need VC6 support, the mingw version should probably be all you need.

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