原來一直使用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
[cpp] view plaincopyprint?
/* 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
用宏替換後,其實就是:
[cpp] view plaincopyprint?
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,沒有用上面的編譯器指令
[cpp] view plaincopyprint?
/* 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
更新:2013/9/14
不過今天開始啓用C++11,現在有了標準的可用。參考文檔:
http://en.cppreference.com/w/cpp/types/integer
幾乎和boost裏面的一樣。所以本文標題也有所改變。
本文轉自 http://blog.csdn.net/csfreebird/article/details/8223166