【小练习】程序设计基本概念:类型转换2

1.练习代码

#include "stdafx.h"
#include <iostream>
#include <string.h>
#include <conio.h>
#include <stdio.h>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	unsigned int a = 0xFFFFFFF7;
	unsigned char i = (unsigned char) a;
	char* b = (char*) &a;

	printf("%08x, %08x\n", i, *b);
	return 0;
}

2.关键点分析

2.1转换过程

#include "stdafx.h"
#include <iostream>
#include <string.h>
#include <conio.h>
#include <stdio.h>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	unsigned int a = 0xFFFFFFF7;
	unsigned char i = (unsigned char) a;
	//unsigned char类型长度为1字节,unsigned int类型长度为4字节
	//此处发生截断,0xFFFFFFF7的0x000000F7被截取赋予i
	char* b = (char*) &a;
	//a的地址被转换成char类型的指针,最初的位置仍指向变量a的起始地址

	printf("%08x, %08x\n", i, *b);
	//规定以%08x十六进制最少输出8位的形式打印两个数字
	//i的值已经被截断,原本0xF7,按十六进制打印8位则为0x000000F7
	//b指针仍指向a的起始地址,按十六进制打印8为仍为0xFFFFFFF7
	return 0;
}

2.2运行结果

【小练习】程序设计基本概念:类型转换2