CITS2002 Systems Programming  
prev
next CITS2002 CITS2002 schedule  

Employing the correct sized integers for portability

In most of our C programming (laboratories and projects) we have employed the standard int datatype whenever we have simply wished to count something, or to loop a small number of times.

We have not cared (probably not even thought) whether the host architecture supported integers of length 16-, 32-, or 64-bits, but have been confident (on laptops and desktops) that integers were at least 32-bits long; meeting our typical requirements.

For different applications, the actual storage size of an integer may be significant, and a portable program should enforce its requirements. For example, if we required an array to store temperature samples on, say, an Internet-of-Things (IoT) device, then an 8-bit integer may be sufficient, or necessary if we required a million of them.

C99 introduced the standard header file <stdint.h> which defines the C99 base types required to employ integers of exactly the required size, together with their limits. An extract:

typedef signed char         int8_t;
typedef short int           int16_t;
typedef int                 int32_t;
# if __WORDSIZE == 64
typedef long int            int64_t;
# else
typedef long long int       int64_t;
# endif
#endif
....
/* Minimum of signed integral types.  */
# define INT8_MIN           (-128)
# define INT16_MIN          (-32767-1)
# define INT32_MIN          (-2147483647-1)
# define INT64_MIN          (-__INT64_C(9223372036854775807)-1)
/* Maximum of signed integral types.  */
# define INT8_MAX           (127)
# define INT16_MAX          (32767)
# define INT32_MAX          (2147483647)
# define INT64_MAX          (__INT64_C(9223372036854775807))

Similar support is provided for unsigned integers, and float-point numbers of different lengths (32-, 64-, 128-bits).

Employing the correct form of these datatypes is critcal in many application domains demanding portable software - including networking protocols, cryptography, and image processing.

 


CITS2002 Systems Programming, Lecture 22, p7, 16th October 2023.