C语言–数据长度、明确数据长度类型
A.数据长度
1)32位机下:
数据类型 | 字节数 | 取值范围 |
---|---|---|
char | 1 | -128~127 |
unsigned char | 1 | 0~255 |
short | 2 | -32768~32767 |
unsigned short | 2 | 0~65535 |
int | 4 | -2147483648~2147483647 |
unsigned int | 4 | 0~4294967295 |
long | 4 | -2147483648~2147483647 |
unsigned long | 4 | 0~4294967295 |
float | 4 | -3.4×10-38~3.4×10-38 |
double | 8 | -1.7×10-308~1.7×10-308 |
bool | 1 | 0,1 |
- | - | - |
short int | 2 | -32768~32767 |
long int | 4 | -2147483648~2147483647 |
long double | 8 | -1.7×10-308~1.7×10-308 |
2)64位机下
数据类型 | 32位 | 64位 |
---|---|---|
char | 1 | 1 |
shot | 2 | 2 |
int | 4 | 4 |
long | 4 | 8 |
float | 4 | 4 |
double | 8 | 8 |
指针 | 4 | 8 |
B.明确数据长度类型
1)例子
int8_t,int16_t,int32_t,int64_t
uint8_t,uint16_t,uint32_t,uint64_t等
2)作用
在A中罗列的变量类型的所需字节大小会随着系统的位数不同而变化,这会给代码在移植、兼容上带来一定的问题,因此出现了“明确数据长度类型”,其不管在什么平台上都是固定的8位、16位、32位、64位。
3)定义
明确数据长度类型intx_t是通过typedef定义的,即其不是一种新的数据类型,具体定义如下:
类型 | 定义(32位机下) |
---|---|
int8_t | typedef signed char int8_t; |
uint8_t | typedef unsigned char uint8_t; |
int16_t | typedef signed short int16_t; |
uint16_t | typedef unsigned short uint16_t |
int32_t | typedef signed int int32_t; |
uint32_t | typedef unsigned int uint32_t; |
int64_t | typedef signed long long int64_t; |
uint64_t | typedef unsigned long long uint64_t; |
这些包含在stdint.h头文件。其中x为固定所需的位数,例如 int8_t 即占1个字节,范围为-128~127。
为了保证intx_t在任何位机下都是x位,在不同位机下(32位或64位)需要使用相应的基本变量类型,例如:
# if __WORDSIZE == 64
typedef long int int64_t;
# else
__extension__
typedef long long int int64_t;