Fixed Width Integers in C ++

Sometimes I need to use fixed-width integers to communicate with external devices such as PLCs. I also use them to define bitmasks and manipulate bits of image data. The AFAIK C99 standard defines fixed-width integers such as int16_t. However, the compiler that I use, VC ++ 2008 does not support C99 and AFAIK. Microsoft has no plans to support it.

My question is, what is the best practice of using fixed-width integers in C ++?

I know that VC ++ defines non-standard fixed-width integers such as __int16, but I hesitate to use a non-standard type. Will the following C ++ standard define fixed-width integers?

+19
c ++ c types portability visual-c ++
Apr 09 '09 at 15:44
source share
6 answers

Boost has a typedef for all types of C99 and more: "Boost integer library"

+12
Apr 09 '09 at 15:52
source share

You can solve this problem with some #ifdef directives.

 #ifdef _MSC_VER typedef __int16 int16_t #else #include <stdint.h> #endif 
+18
Apr 09 '09 at 15:47
source share

Include the <stdint.h> file to get definitions for types of type uint16_t . By default, VC ++ does not come with <stdint.h> , but you can get this file from several places. Wikipedia lists a few, and Google will find you much more.

+7
Apr 09 '09 at 15:50
source share

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

Yes.

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

+3
Apr 09 '09 at 15:50
source share

I used the D20 version owned by Danny Smith, available in the mingw package:

I had to configure this version to compile with some non VC 8 compilers (mainly VC6) - it served me well.

Perhaps the other day I will talk about my version compatible with VC6. The changes were pretty minor - just some macro definitions for using VC6 specific keywords for 64-bit types. If you don't need VC6 support, the mingw version should be all you need.

+1
Apr 09 '09 at 16:09
source share

There are different ways. In most environments, it will be established that short int is 16 bits and long int is 32 bits. ( long implied when you simply declare an int .) If you typedef your own type int16, you will probably end up using short int .

Another possibility is bit fields in structures. You can say something like:

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

And so on. If you then define:

 struct x myvar; myvar.a = 54; 

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

0
Apr 09 '09 at 15:52
source share



All Articles