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

相关文章:

  • 2021-07-21
  • 2021-04-22
  • 2021-08-27
  • 2021-12-07
  • 2021-11-03
  • 2022-02-11
  • 2022-01-20
  • 2021-05-18
猜你喜欢
  • 2021-05-01
  • 2021-05-22
  • 2021-10-27
  • 2022-12-23
  • 2021-06-22
  • 2021-12-24
  • 2022-02-28
相关资源
相似解决方案