boost跨平台C++整数部类 之一 固定宽度整数

boost跨平台C++整数类型 之一 固定宽度整数

原来一直使用ACE的跨平台整数类型,比如:ACE_UINT32, 但是自己使用C++的风格是明显的现代风格,以范型为主,所以最近开始逐步替换ACE的代码,改用boost库。

在boost库中,standard integer types用来支持跨平台的整数类型,我用的是1.48版本,参考文档:

http://www.boost.org/doc/libs/1_48_0/libs/integer/doc/html/boost_integer/cstdint.html

boost库的整数实现基于99 C标准,不选98C++标准为基础是因为有些情况下的未定义行为。将来新的C++标准如果规定了跨平台整数类型的话,boost的这个库可能被废除。不过现在C++11还没有编译器完全支持,也没有太多选择。

自己实现固然可以,不过意味着分发困难和很多测试,看明白boost如何实现的就可以了。没必要自己干这胀活吧。

注意,总是使用boost::开头的类型和模板,不要直接使用boost引入的C的标准类型和宏。

现在开始。

boost提供了精确宽度的整数类型,采用int#_t 命名,#就是位数,比如int8_t 代表有符号的8位整数。那么它的真实对应物是什么?

注意,我这里是Ubuntu 64bit, GCC4.6.3, boost 1.48.0

/* For GCC 2.7 and later, we can use specific type-size attributes.  */
# define __intN_t(N, MODE) \
  typedef int int##N##_t __attribute__ ((__mode__ (MODE)))
# define __u_intN_t(N, MODE) \
  typedef unsigned int u_int##N##_t __attribute__ ((__mode__ (MODE)))

# ifndef __int8_t_defined
#  define __int8_t_defined
__intN_t (8, __QI__);
__intN_t (16, __HI__);
__intN_t (32, __SI__);
__intN_t (64, __DI__);
# endif


用宏替换后,其实就是:

typedef int int8_t __attribute__ ((__mode__ (__QI__)))
用到了几个GCC编译器的指令

__attribute__, __mode和 __QI__


##是宏的连接符号。


这篇帖子解释了这些指令:http://stackoverflow.com/questions/4559025/what-does-gcc-attribute-modexx-actually-do

__QI__就代表最小寻址单元,一个字节,8位。

__HI__ 以及后面的指令都是8位的若干倍数。


至于无符号固定宽度整数类型,前面加上u,形如:uint#_t 就是无符号整数的固定宽度表达方法。

实现采用了另一套typedef,没有用上面的编译器指令

/* Unsigned.  */
typedef unsigned char		uint8_t;
typedef unsigned short int	uint16_t;
#ifndef __uint32_t_defined
typedef unsigned int		uint32_t;
# define __uint32_t_defined
#endif
#if __WORDSIZE == 64
typedef unsigned long int	uint64_t;
#else
__extension__
typedef unsigned long long int	uint64_t;
#endif