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;
#else
#error No 8 bits integer type for this platform
#endif

// 16 bits integer types
#if USHRT_MAX == 0xFFFF
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;
#else
#error No 16 bits integer type for this platform
#endif

// 32 bits integer types
#if USHRT_MAX == 0xFFFFFFFF
typedef signed short int32;
typedef unsigned short uint32;
#elif UINT_MAX == 0xFFFFFFFF
typedef signed int int32;
typedef unsigned int uint32;
#elif ULONG_MAX == 0xFFFFFFFF
typedef signed long int32;
typedef unsigned long uint32;
#else
#error No 32 bits integer type for this platform
#endif

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


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


// define a float type
typedef float my_float;

// define a double type
typedef double my_double;

No comments: