c++程序设计的问题

来源:百度知道 编辑:UC知道 时间:2024/06/13 09:03:50
#include<iostream.h>
#include<iomanip.h>
struct tag
{
char low,high;
};
union word1
{
struct tag byte;
short int word;
}w;
void main()
{
w.word=0x00004241;//这句什么意思?
cout<<"word value:"<<hex<<w.word<<endl;//???这个怎样分析???
cout<<"low value:"<<hex<<w.byte.low<<endl;
cout<<"high value:"<<hex<<w.byte.high<<endl;
}

执行结果;
word value:4241//怎样分析?
low value:A//(我分析这里应该是B,因为42表示B,而w.byte.low表示结构中的第一个变量,应该是B啊,为什么是A.???)
high value B

hex对象可以将输入的数字转换为十六进制

w.word=0x00004241;//这里就是将十六进制数字4241赋予w.word

cout<<"word value:"<<hex<<w.word<<endl;//这里以十六进制输出保存在w.word中的数字,也就是上面的4241

low value:A //这里就涉及到数据在计算机中的保存方式的问题了,w.byte.low取了4241的低8位,w.byte.high则取了4241的高8位

首先,看这个union word1
因为tag中有两个char因此实际这个union的成员变量有三个
char
char
short int
那么这个union所占字节数与其最宽的short相同,即2个Byte
w.word=0x00004241,把这个union的区域低8位赋值为16进制的41,把高8位赋值成16进制的42。
w.word包含整个2个Byte的内容,因此输出4241,
而w.byte.low由于low先于high定义,因此low处在低8位,high处在高8位,所以结果如此。

另外
cout<<"low value:"<<hex<<w.byte.low<<endl;
cout<<"high value:"<<hex<<w.byte.high<<endl;
这两句中的hex没有实际意义。