例如 int这个数据类型所占的字节数是2 取值范围是-32768-32767
请问它是通过什么公式换算成的?
具体的原理是什么?
请哥们解答解答。
Cè¯è¨ä¸çæ°æ®ç±»åï¼ç®åçå¯ä»¥å为æ´æ°ç±»ååæµ®ç¹æ°ç±»åãæå åèæ°ä¸åå¼èå´çå ³ç³»å®é ä¸æ¯æ´æ°ç¼ç åæµ®ç¹æ°ç¼ç çé®é¢ï¼æ´æ°ç¼ç çä¸ç§æ¹å¼æ¯åç ãåç ãè¡¥ç ï¼å¾å®¹æç解ï¼æµ®ç¹æ°çç¼ç æ ¼å¼ä½¿ç¨çæ¯IEEE754ç¼ç ã
1ãæ´æ°ç¼ç 以å符类å为ä¾ã
å符类åå 1个åèï¼å ±8ä½äºè¿å¶bitä½ï¼å æ¤æåç»åæ°ï¼æ2^8 = 256ç§ç¼ç çæ¹æ³ãå¦æ表示æ 符å·å符类åï¼é£ä¸è¬æ¥è¯´è¡¨ç¤ºã0ï¼255ãè¿256个æ°ã
å¦æ表示æ符å·charç±»åï¼å¦æ表示æ£æ°ï¼é£æé«ä½ç¬¦å·ä¸º0ï¼å æ¤å¯è¡¨ç¤ºçææ£æ´æ°æ¯:
0-111 1111 ï¼è½¬åæåè¿å¶å°±æ¯127ãåæ ·çéçï¼ç¬¦å·ä¸º1表示è´æ°ãæå°çè´æ°æ¯
1-000 0000ï¼è½¬åæåè¿å¶æ°å°±æ¯-128ï¼å æ¤æ符å·charç±»å表示çèå´æ¯[-128,127]ã
ä¸è¬æ¥è¯´ï¼å设æ´åæ°æ®ç±»åå çäºè¿å¶ä½æ°nï¼å¦æ表示æ 符å·æ´æ°ååå¼èå´æ¯[0,2^n-1]ï¼å¦æ表示æ符å·æ´æ°ï¼ã-2^(n-1) , 2^(n-1) - 1] ã
2ãæµ®ç¹æ°ç±»å
æµ®ç¹æ°ç¼ç ä¸è¬éç¨çæ¯IEEE754çç¼ç è§åï¼è¿ä¸ªç¼ç æ ¼å¼ä¸»è¦æåºäºæµ®ç¹æ°æææ°åãææ°ä»¥å符å·ä½æå çäºè¿å¶ä½æ°ãç®åæ¦æ¬ä¸ºï¼
æ ¼å¼ é¿åº¦ 符å·ä½ ææ°ä½ å°¾æ°ä½ ææä½æ° ææ°å移 å°¾æ°è¯´æ
å精度 32 1 8 23 24 127 æä¸ä½éå«ä½
å精度 64 1 11 52 53 1023 æä¸ä½éå«ä½
æ©å±å精度 80 1 15 64 64 16383 没æéå«ä½
注æï¼æ©å±åç²¾åº¦æ ¼å¼æ²¡æéå«ä½ï¼å æ¤å®çææä½æ°ä¸å°¾æ°ä½æ°ä¸è´ï¼èå精度ååç²¾åº¦æ ¼å¼åæä¸ä½éå«ä½ï¼å æ¤å®ä»¬çææä½æ°æ¯å°¾æ°ä½æ°å¤1ã
ä¸è¬å¾å°èªå·±æå¨æ¥ç®æµ®ç¹æ°çåå¼èå´ï¼å¯ä»¥ä½¿ç¨å¦ä¸ç¨åºæ¥è®¡ç®ã
#include <stdio.h>typedef struct FP_SINGLE
{
unsigned __int32 fraction : 23;
unsigned __int32 exp : 8;
unsigned __int32 sign : 1;
} fp_single;
typedef struct FP_DOUBLE
{
unsigned __int64 fraction : 52;
unsigned __int64 exp : 11;
unsigned __int64 sign : 1;
} fp_double;
typedef struct FP_EX_DOUBLE
{
unsigned __int64 fraction;
unsigned __int32 exp : 15;
unsigned __int32 sign : 1;
} fp_ex_double;
int main()
{
float x;
fp_single * fp_s = (fp_single *)&x;
fp_s->sign = 0;
fp_s->exp = 0xfe;
fp_s->fraction = 0x7fffff;
printf ("float æ大æ°ï¼ %le\n",(double)x);
fp_s->sign = 0;
fp_s->exp = 0x1;
fp_s->fraction = 0x0;
printf ("float æå°æ°ï¼ %le\n",(double)x);
fp_s->sign = 0;
fp_s->exp = 0;
fp_s->fraction = 0x1;
printf ("float æå°å¼±è§èæ°ï¼%le\n\n",(double)x);
double y;
fp_double * fp_d = (fp_double *)&y;
fp_d->sign = 0;
fp_d->exp = 0x7fe;
fp_d->fraction = 0xfffffffffffff;
printf ("double æ大æ°ï¼ %le\n", y);
fp_d->sign = 0;
fp_d->exp = 0x1;
fp_d->fraction = 0x0;
printf ("double æå°æ°ï¼ %le\n", y);
fp_d->sign = 0;
fp_d->exp = 0;
fp_d->fraction = 0x1;
printf ("double æå°å¼±è§èæ°ï¼%le\n\n", y);
char ch[10];
fp_ex_double * fp_ex_d = (fp_ex_double *)ch;
fp_ex_d->sign = 0;
fp_ex_d->exp = 0x7ffe;
fp_ex_d->fraction = 0xffffffffffffffff;
// ä¸ç¥éæ©å±å精度浮ç¹æ°å¦ä½è¾åºï¼
// ä¸è¿å¯ä»¥ç¨odè·è¸ªï¼ç¶åæ¾å°ch[0]çå°åï¼å¨æ°æ®çªå£ä¸éæ© æµ®ç¹ 80为é¿å精度ï¼
// å°±å¯ä»¥çå°æ°å¼äºã
fp_ex_d->sign = 0;
fp_ex_d->exp = 0x1;
fp_ex_d->fraction = 0x8000000000000000;
fp_ex_d->sign = 0;
fp_ex_d->exp = 0;
fp_ex_d->fraction = 0x1;
return 0;
}
顺便说一下,现在好多编译器里的int都是32位的,即int和long int是一样的。本回答被提问者采纳
若是有符号的int,那么除去一个符号位,还有15位,
所以取值范围是
非负数:2^15-1 到 0
负数:-1 到 - 2^15
所以int的取值范围是 -32768到32767
如果是无符号的int,那么取值范围是2^16-1 到0
就是 0到65535
2的16次方