跨平台C语言,double、long、unsigned、int、char类型数据所占字节数

来源:互联网 发布:matlab 数组写入txt 编辑:程序博客网 时间:2024/06/01 21:14

和机器字长及编译器有关系:所以,int,long int,short int的宽度都可能随编译器而异。但有几条铁定的原则(ANSI/ISO制订的): 1 sizeof(short int)<=sizeof(int) 2 sizeof(int)<=sizeof(long int) 3 short int至少应为16位(2字节) 4 long int至少应为32位。 unsigned 是无符号的意思。例如:

16位编译器

char :1个字节char*(即指针变量): 2个字节short int : 2个字节int: 2个字节unsigned int : 2个字节float: 4个字节double: 8个字节long: 4个字节long long: 8个字节unsigned long: 4个字节

32位编译器

char :1个字节char*(即指针变量): 4个字节(32位的寻址空间是2^32, 即32个bit,也就是4个字节。同理64位编译器)short int : 2个字节

int: 4个字节unsigned int : 4个字节float: 4个字节double: 8个字节long: 4个字节long long: 8个字节unsigned long: 4个字节

64位编译器

char :1个字节char*(即指针变量): 8个字节short int : 2个字节int: 4个字节unsigned int : 4个字节float: 4个字节double: 8个字节long: 8个字节long long: 8个字节unsigned long: 8个字节

uint8_t / uint16_t / uint32_t /uint64_t  等数据类型

在nesc的代码中,你会看到很多你不认识的数据类型,比如uint8_t等。咋一看,好像是个新的数据类型,不过C语言(nesc是C的扩展)里面好像没有这种数据类型啊!怎么又是u又是_t的?很多人有这样的疑问。_t的意思表示什么?它就是一个结构的标注,可以理解为type/typedef的缩写,表示它是通过typedef定义的,而不是其它数据类型。

uint8_t,uint16_t,uint32_t等都不是什么新的数据类型,它们只是使用typedef给类型起的别名。不过,不要小看了typedef,它对于你代码的维护会有很好的作用。比如C中没有bool,于是在一个软件中,一些程序员使用int,一些程序员使用short,会比较混乱,最好就是用一个typedef来定义,如:
typedef char bool;

一般来说,一个C的工程中一定要做一些这方面的工作,因为你会涉及到跨平台,不同的平台会有不同的字长,所以利用预编译和typedef可以让你最有效的维护你的代码。为了用户的方便,C99标准的C语言硬件为我们定义了这些类型,我们放心使用就可以了。

 按照posix标准,一般整形对应的*_t类型为:
1字节     uint8_t
2字节     uint16_t
4字节     uint32_t
8字节     uint64_t

附:C99标准中inttypes.h的内容

/*   inttypes.h   Contributors:     Createdby Marek Michalkiewicz <marekm@linux.org.pl>   THISSOFTWARE IS NOT COPYRIGHTED   Thissource code is offered for use in the public domain.  You may   use,modify or distribute it freely.   Thiscode is distributed in the hope that it will be useful, but   WITHOUTANY WARRANTY.  ALLWARRANTIES, EXPRESS OR IMPLIED ARE HEREBY   DISCLAIMED.  This includes but is not limited towarranties of   MERCHANTABILITYor FITNESS FOR A PARTICULAR PURPOSE. */#ifndef __INTTYPES_H_#define __INTTYPES_H_/* Use [u]intN_t if you need exactly N bits.   XXX- doesn't handle the -mint8 option.  */typedefsigned char int8_t;typedefunsigned char uint8_t;typedefint int16_t;typedefunsigned int uint16_t;typedeflong int32_t;typedefunsigned long uint32_t;typedeflong long int64_t;typedefunsigned long long uint64_t;typedefint16_t intptr_t;typedefuint16_t uintptr_t;#endif

输入输出的方法

vc6.0为例:

#include<stdio.h>typedef unsigned __int16 uint16_t;typedef unsigned __int32 uint32_t;typedef unsigned __int64 uint64_t;int main(){uint64_t num;uint32_t num1;uint16_t num2;scanf("%I64u",&num);scanf("%I32u",&num1);scanf("%I16u",&num2);printf("%I64u\n",num);printf("%I64u\n",num1);printf("%I64u\n",num2);printf("%d\n",sizeof(num));printf("%d\n",sizeof(num1));printf("%d\n",sizeof(num2));return 0;}



阅读全文
0 0
原创粉丝点击