C语言中关于符号问题的解析
1.C语言中各种数据类型所占空间的大小分别为:
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdbool.h>
int main()
{
printf("布尔类型:%d\n",sizeof(bool));
printf("字符型:%d\n",sizeof(char));
printf("短整型:%d\n",sizeof(short));
printf("整型:%d\n",sizeof(int));
printf("浮点型:%d\n",sizeof(float));
printf("长整型:%d\n",sizeof(long));
printf("双精度类型:%d\n",sizeof(double));
printf("长长整形:%d\n",sizeof(long long));
system("pause");
return 0;
}
输出结果:
2.一个无符号字符型的数取值范围是多少:
char类型一般为一个字节,范围是-128~127之间,unsigned char无符号,范围为0~255之间
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdbool.h>
void main()
{
for (unsigned char i = 0; i < 256; ++i)
{
printf("Hello c.\n");
}
}
输出结果:
由于unsigned char型的值不能大于255所以程序会死循环
3.有符号数和无符号数在内存中的存储:
无符号数的所有位都是数据位,所以内存中的存储就是数据本身;
有符号数要通过内存中存储的补码求出原码;
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdbool.h>
void main()
{
int a = -1;
printf("%d\n", a);
printf("%u\n", a);
system("pause");
}
输出结果:
在内存中a=-1的存储方式为:ff ff ff ff
4.大小端存储模式:
大端(存储)模式:是指一个数据的低位字节序的内容放在高地址处,高位字节序存的内容放在低地址处。
小端(存储)模式:是指一个数据的低位字节序内容存放在低地址处,高位字节序的内容存放在高地址处。
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdbool.h>
void main()
{
int a = 1;
}
这是小端存储模式(大端与之相反):
检查机器是大端还是小端存储:
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdbool.h>
bool checkmodel()
{
int i = 1;
return (*(char*)&i);
}
void main()
{
bool flag = checkmodel();
if (flag)
{
printf("this is a little\n");
}
else
{
printf("this is a big\n");
}
system("pause");
}
输出结果:
5.有符号数和无符号数的输出:
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
int main()
{
char a = -1;
signed char b = -1;
unsigned char c = -1;
printf("a=%d\nb=%d\nc=%d\n", a, b, c);
system("pause");
}
输出结果:
6.无符号整型的取值范围:0~2^32-1
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdbool.h>
int main()
{
unsigned int i;
for (i = 9; i >= 0; i--)
printf("%u\n", i);
system("pause");
return 0;
}
输出结果:
7.有符号字符型的取值范围:-128~127
从a[0]~a[127]:是128次循环;
从a[128]~a[254]:是127次循环;
a[255]是\0故不算在内,得最终结果255
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdbool.h>
int main()
{
char a[1000];
int i;
for (i = 0; i < 1000; i++)
{
a[i] = -1 - i;
}
printf("%d", strlen(a));
system("pause");
return 0;
}
输出结果: