對於一些常用數據類型的理解

對於一些常用數據類型的理解

在上個項目的網絡編程中,遇到了很多typedef定義的數據類型,現進行記錄,主要參考了一下鏈接:

https://blog.csdn.net/EUSIA/article/details/76401235
https://www.cnblogs.com/curo0119/p/8891906.html
https://www.jb51.net/article/109690.htm
https://blog.csdn.net/yz930618/article/details/84785970

int_t同類

int_t 爲一個結構的標註,可以理解爲type/typedef的縮寫,表示它是通過typedef定義的,而不是一種新的數據類型。因爲跨平臺,不同的平臺會有不同的字長,所以利用預編譯和typedef可以最有效的維護代碼
他們在stdint.h中定義如下:

/* Signed. */
/* There is some amount of overlap with <sys/types.h> as known by inet code */
#ifndef __int8_t_defined
# define __int8_t_defined
typedef signed char       int8_t;
typedef short int        int16_t;
typedef int           int32_t;
# if __WORDSIZE == 64
typedef long int        int64_t;
# else
__extension__
typedef long long int      int64_t;
# endif
#endif
 
/* 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

其表示的範圍如下表所示:

Specifier Common Equivalent Signing Bits Bytes Minimum Value Maximum Value
int8_t signed char signed 8 1 -128 128
uint8_t unsigned char unsigned 8 1 0 255
int16_t short signed 16 2 -32768 32767
uint16_t unsigned short unsigned 16 2 0 65535
int32_t int signed 32 4 -2147483648 2147482647
uint32_t unsigned int unsigned 32 4 0 4294967295
int64_t long long signed 64 8 9223372036854770000 9223372036854770000
uint64_t unsigned long long unsigned 64 8 0 18446744073709500000

size_t與ssize_t

size_t主要用於計數,如sizeof函數返回值類型即爲size_t。在不同位的機器中所佔的位數也不同,size_t是無符號數,ssize_t是有符號數。

在32位機器中定義爲:typedef  unsigned int size_t; (4個字節)
在64位機器中定義爲:typedef  unsigned long size_t;(8個字節)

由於size_t是無符號數,因此,當變量有可能爲負數時,必須使用ssize_t。因爲當有符號整型和無符號整型進行運算時,有符號整型會先自動轉化成無符號。
此外,int 無論在32位還是64位機器中,都是4個字節, 且帶符號,可見size_t與int 的區別之處。

各數據類型輸入輸出符

有時候做調試的時候,對於各種類型,其輸出格式也會有所不同,主要如下所示:

int8_t:%c;
uint8_t:%c;

int16_t: %hd;
uint16_t:%hu;

int32_t:%d;
uint32_t:%u;

int64_t:%l64d;
uint64_t:%l64u;

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