Wednesday, July 1, 2009

Portable fixed-size types

Everyone knows this but still felt like posting it.

When you are porting an application across OS, the first thing that comes to bug you is the size difference in basic data types. A basic int can be 16 bit in some, 32 in other and 64 bit in others. If you are going to port an application which depends on the data size and they are using the original data types, then its better you forget the porting work. Time to look for a job change ;-)

For some time now I am working on an application which is being supported on almost all the platforms. I was amazed to see at what ease the application was ported to newer platforms be it 32 bit or 64 bit. Such kind of easiness was due to how we used basic types. They created portable fixed size data types....

Here is a small implementation...

// Define portable fixed-size types

#include < limits.h>

// 8 bits integer types
#if UCHAR_MAX == 0xFF
typedef signed char int8;
typedef unsigned char uint8;
#error No 8 bits integer type for this platform

// 16 bits integer types
typedef signed short int16;
typedef unsigned short uint16;
#elif UINT_MAX == 0xFFFF
typedef signed int int16;
typedef unsigned int uint16;
#elif ULONG_MAX == 0xFFFF
typedef signed long int16;
typedef unsigned long uint16;
#error No 16 bits integer type for this platform

// 32 bits integer types
typedef signed short int32;
typedef unsigned short uint32;
typedef signed int int32;
typedef unsigned int uint32;
typedef signed long int32;
typedef unsigned long uint32;
#error No 32 bits integer type for this platform

// 64 bits integer types
typedef signed __int64 int64;
typedef unsigned __int64 uint64;
#elseif defined(alpha) || defined(__x86_64__)
typedef signed long int64;
typedef unsigned long uint64;
typedef signed long long int64;
typedef unsigned long long uint64;
#error Not possible to define ev_uint64

// define a boolean type
typedef enum my_bool { TRUE = 1, FALSE = 0 };

// define a float type
typedef float my_float;

// define a double type
typedef double my_double;

No comments: