uint8_t / uint16_t / uint32_t /uint64_t詳解

 

在C語言中有6種基本數據類型:short、int、long、float、double、char

1)整型:short int、int、long int

2)浮點型:float、double

3)字符類型:char

因此,uint8_t / uint16_t / uint32_t /uint64_t這些數據類型都只是別名。這些數據類型中都帶有_t, _t 表示這些數據類型是通過typedef定義的,而不是新的數據類型。

那麼_t的意思到底表示什麼?它就是一個結構的標註,可以理解爲type/typedef的縮寫,表示它是通過typedef定義的。

一般來說,一個C的工程中一定要做一些這方面的工作,因爲你會涉及到跨平臺,不同的平臺會有不同的字長,所以利用預編譯和typedef可以讓你最有效的維護你的代碼。爲了用戶的方便,C99標準的C語言硬件爲我們定義了這些類型,我們放心使用就可以了。 按照posix標準,一般整形對應的*_t類型爲: 1字節 uint8_t 2字節 uint16_t 4字節 uint32_t 8字節 uint64_t

typedef   signed          char int8_t;
typedef   signed short     int int16_t;
typedef   signed           int int32_t;
typedef   signed       __INT64 int64_t;
 
/* exact-width unsigned integer types */
typedef unsigned          char uint8_t;
typedef unsigned short     int uint16_t;
typedef unsigned           int uint32_t;
typedef unsigned       __INT64 uint64_t;
 
/* 7.18.1.2 */
/* smallest type of at least n bits */
/* minimum-width signed integer types */
typedef   signed          char int_least8_t;
typedef   signed short     int int_least16_t;
typedef   signed           int int_least32_t;
typedef   signed       __INT64 int_least64_t;
 
/* minimum-width unsigned integer types */
typedef unsigned          char uint_least8_t;
typedef unsigned short     int uint_least16_t;
typedef unsigned           int uint_least32_t;
typedef unsigned       __INT64 uint_least64_t;
 
/* 7.18.1.3 */
/* fastest minimum-width signed integer types */
typedef   signed           int int_fast8_t;
typedef   signed           int int_fast16_t;
typedef   signed           int int_fast32_t;
typedef   signed       __INT64 int_fast64_t;
 
/* fastest minimum-width unsigned integer types */
typedef unsigned           int uint_fast8_t;
typedef unsigned           int uint_fast16_t;
typedef unsigned           int uint_fast32_t;
typedef unsigned       __INT64 uint_fast64_t;
 
/* 7.18.1.4 integer types capable of holding object pointers */
#if __sizeof_ptr == 8
typedef   signed       __INT64 intptr_t;
typedef unsigned       __INT64 uintptr_t;
#else
typedef   signed           int intptr_t;
typedef unsigned           int uintptr_t;
#endif
 
/* 7.18.1.5 greatest-width integer types */
typedef   signed     __LONGLONG intmax_t;
typedef unsigned     __LONGLONG uintmax_t;

注意:

typedef unsigned char uint8_t;

必須小心 uint8_t 類型變量的輸出。uint8_t類型變量轉化爲字符串時得到的會是ASCII碼對應的字符, 字符串轉化爲 uint8_t 變量時, 會將字符串的第一個字符賦值給變量.

uint8_t fieldID = 67;
cerr<< "field=" << fieldID <<endl;

field=C

uint8_t fieldID = 67;
cerr<< "field=" << (uint16_t) fieldID <<endl;

結果是:field=67

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章