2007/07/07(土)プラットホーム汎用で、固定長の整数型を使う

int型は整数型ですが、int や long や long long などは環境によってサイズが違ったりします。これらの型は、元もとサイズ(バイト長)を固定する目的で作られたものではないからです。

プラットホーム汎用でプログラムを書く際、固定長のデータを扱う時(バイナリデータ列など)は特に注意する必要があります。C99という規格で固定長整数型として int32t などが規定されましたが、すべての環境で使えるわけではありません。また Windows プラットホームならば、__int32 などが利用出来ますが、Windows以外では利用出来ません。

自分は、だいたいの環境でうまく動くマクロを作って、これを使っています。

#if defined(__C99__) || (defined(__GNUC__) && __GNUC__ >= 3)
#	include <inttypes.h>
#	include <stdint.h>
#else
#	if defined(__GNUC__)
		typedef short			 int16_t;
		typedef unsigned short		uint16_t;
		typedef int			 int32_t;
		typedef unsigned int		uint32_t;
		typedef long long		 int64_t;
		typedef unsigned long long	uint64_t;
#	elif (_MSC_VER || __BORLANDC__)
		typedef __int16			 int16_t;
		typedef unsigned __int16	uint16_t;
		typedef __int32			 int32_t;
		typedef unsigned __int32	uint32_t;
		typedef __int64			 int64_t;
		typedef unsigned __int64	uint64_t;
#	endif
#endif