零扩展:将一个无符号数转换成一个更大的数据类型,我们只需简单的在表示开头添加0,这种运算称为零扩展。
符号扩展:将一个补码数字转换成为一个更大的数据类型可以执行符号扩展,规则是在表示中添加最高有效位置的副本。
看一下一个代码:
#include <iostream>
using namespace std;
typedef unsigned char* byte_pointer;
void show_bytes(byte_pointer start, int len)
{
int i;
for(i=0; i<len; i++)
{
printf("%.2x", start[i]);
}
printf("\n");
}
void show_int(int x)
{
show_bytes((byte_pointer)&x, sizeof(int));
}
void show_float(float x)
{
show_bytes((byte_pointer)&x, sizeof(float));
}
void show_pointer(void* x)
{
show_bytes((byte_pointer)&x, sizeof(void *));
}
int main()
{
short sx = -12345; //-12345 十六进制0xFFFFCFC7
unsigned short usx = sx; //53191 十六进制0x0000CFC7
int x = sx; //-12345
unsigned ux = usx; //53191
printf("sx = %d:\t", sx);
show_bytes((byte_pointer)&sx, sizeof(short));
printf("usx = %u:\t", usx);
show_bytes((byte_pointer)&usx, sizeof(unsigned short));
printf("x = %d:\t", x);
show_bytes((byte_pointer)&sx, sizeof(int));
printf("ux = %du:\t", ux);
show_bytes((byte_pointer)&ux, sizeof(unsigned));
system("pause");
return 0;
}
运行结果:
-12345 的十六进制是0xFFFFCFC7,53191 的十六进制是0x0000CFC7,前者使用的是符号扩展——最开头加了16位,都是最高有效位1,表示为十六进制就是0xFFFF;后者使用16个0来扩展,表示为0x0000.
位向量[101]表示值-4+1 = -3.
应用符号扩展,得到位向量[1101],表示的值是-8+4+1 = -3.
可以看出,对于w=4,最高两位的组合值是-8+4 = -4,与w=3时符号值相同。类似的,位向量[111]和[1111]都表示值-1.
注意:从一个数据大小到另一数据大小的转换,转换的相对顺序能够影响一个程序的行为。
考虑以下代码:
#include <iostream>
using namespace std;
typedef unsigned char* byte_pointer;
void show_bytes(byte_pointer start, int len)
{
int i;
for(i=0; i<len; i++)
{
printf("%.2x", start[i]);
}
printf("\n");
}
void show_int(int x)
{
show_bytes((byte_pointer)&x, sizeof(int));
}
void show_float(float x)
{
show_bytes((byte_pointer)&x, sizeof(float));
}
void show_pointer(void* x)
{
show_bytes((byte_pointer)&x, sizeof(void *));
}
int main()
{
short sx = -12345;
unsigned uy = sx;
printf("uy = %u:\t", uy);
show_bytes((byte_pointer)&uy, sizeof(unsigned));
system("pause");
return 0;
}
运行结果:
uy = 4294954951: c7cfffff
这表明当把short转换成unsigned时,我们要先改变大小,之后在完成从有符号数到无符号数的转换。即就是说(unsigned)sx等价于(unsignde)(int)sx,求值得到4294954951,而不等价于(unsignde)(unsigned short)sx,后者求值得到53191.