工作中经常碰到int8_t、int16_t、int32_t、int64_t、uint8_t、size_t、ssize_t等数据类型,所以有必要对此进行梳理。

int_t同类

int_t 为一个结构的标注,可以理解为type/typedef的缩写,表示它是通过typedef定义的,而不是一种新的数据类型。因为跨平台,不同的平台会有不同的字长,所以利用预编译和typedef可以最有效的维护代码。

  • int8_t : typedef signed char;
  • uint8_t : typedef unsigned char;
  • int16_t : typedef signed short ;
  • uint16_t : typedef unsigned short ;
  • int32_t : typedef signed int;
  • uint32_t : typedef unsigned int;
  • int64_t : typedef signed long long;
  • uint64_t : typedef unsigned long long;
Specifier Common Equivalent Signing Bits Bytes Minimum Value Maximum Value
int8_t signed char Signed 8 1 -128 127
uint8_t unsigned char Unsigned 8 1 0 255
int16_t short Signed 16 2 -32,768 32,767
uint16_t unsigned short Unsigned 16 2 0 65,535
int32_t int Signed 32 4 -2,147,483,648 2,147,483,647
uint32_t unsigned int Unsigned 32 4 0 4,294,967,295
int64_t long long Signed 64 8 -9,223,372,036,854,775,808 9,223,372,036,854,775,807
uint64_t unsigned long long Unsigned 64 8 0 18,446,744,073,709,551,615

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。因为当有符号整型和无符号整型进行运算时,有符号整型会先自动转化成无符号。

1
2
3
4
5
6
7
8
int main()
{
unsigned short a;
short int b = -1;
a = b;
cout << "b=" << b << endl; //b=-1
cout << "a=" << a << endl; //a=65535
}

此外,int 无论在32位还是64位机器中,都是4个字节, 且带符号,可见size_t与int 的区别之处。

下面是stdint.h中的详细定义

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/* 7.18.1.1  Exact-width integer types */
typedef signed char int8_t;
typedef unsigned char uint8_t;
typedef short int16_t;
typedef unsigned short uint16_t;
typedef int int32_t;
typedef unsigned uint32_t;
__MINGW_EXTENSION typedef long long int64_t;
__MINGW_EXTENSION typedef unsigned long long uint64_t;

/* 7.18.1.2 Minimum-width integer types */
typedef signed char int_least8_t;
typedef unsigned char uint_least8_t;
typedef short int_least16_t;
typedef unsigned short uint_least16_t;
typedef int int_least32_t;
typedef unsigned uint_least32_t;
__MINGW_EXTENSION typedef long long int_least64_t;
__MINGW_EXTENSION typedef unsigned long long uint_least64_t;

/* 7.18.1.3 Fastest minimum-width integer types
* Not actually guaranteed to be fastest for all purposes
* Here we use the exact-width types for 8 and 16-bit ints.
*/
typedef signed char int_fast8_t;
typedef unsigned char uint_fast8_t;
typedef short int_fast16_t;
typedef unsigned short uint_fast16_t;
typedef int int_fast32_t;
typedef unsigned int uint_fast32_t;
__MINGW_EXTENSION typedef long long int_fast64_t;
__MINGW_EXTENSION typedef unsigned long long uint_fast64_t;

/* 7.18.1.5 Greatest-width integer types */
__MINGW_EXTENSION typedef long long intmax_t;
__MINGW_EXTENSION typedef unsigned long long uintmax_t;