C语言中类型转换时的截取规则及补码表示的计算方法

本文通过编写程序来验证CSAPP书籍中关于程序转换和数据流的知识,直观展示了不同类型转换和数据流处理的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<iostream>
#include<stdlib.h>
#include<string.h>
#include<math.h>

using namespace std;
/*
看CSAPP书时,看的头晕,直接写个程序验证一下,看起来直观多了。
*/
void typeConvert()
{
	int a = 128;
	char c = a;
	printf("%d\n", c);// (-1)*2^8 = -128
	a = 130;
	c = a;
	printf("%d\n", c);// (-1)*2^8 + 2 = -126

	a = (int)pow(2, 30) + (int)pow(2, 16) + 2;
	short b = a;
	printf("%d\n", b);// b = 2

	a = (int)pow(2, 30) + (int)pow(2, 15) + 2;
	b = a;
	printf("%d\n", b);// b = -32766  b = (-1)*2^15 + 1*2^1 = -32766
	//printf("%d\n", a);// a = 32770    2^15 = 32768

	unsigned short int d = a;
	printf("%d\n", d); // d = 32770 
	a = (int)pow(2, 30) + (int)pow(2, 16) + 2;
	d = a;
	printf("%d\n", d); // d = 2

	b = -2;
	a = (int)b;
	printf("%d\n", a);//a = -2
	printf("%c\n", (char)a);// ?
	printf("%c\n", -4);// ?  char类型值小于0时 输出为?

	unsigned int ua = b;
	printf("%d\n", ua);  // ua = -2
	ua = (unsigned int)b;
	printf("%d\n", ua);//ua = -2
}

void test_ctrlZ()//ctrl+z结束输入流
{
	int a;
	while(cin >> a)
		cout << a << " ";
}

int main()
{
	//typeConvert();
	test_ctrlZ();
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值