今天一個(gè)很偶然的機(jī)會(huì),需要回答一個(gè)將無符號(hào)數(shù)據(jù)存到有符號(hào)變量的問題。我編碼如下,結(jié)果很有意思,我是在VC6里調(diào)試的,有高人看到可否幫忙指點(diǎn)下。
int main()
{
unsigned short temp1 = 65535;
short temp2 = temp1;
unsigned short temp3 = (unsigned short)temp2;
unsigned short temp4 = temp2;
int temp5 = temp2;
unsigned int temp6 = temp2;
unsigned long temp7 = temp2;
int temp8 = (unsigned short)temp2;
short temp9 = temp2;
printf("temp1 = %d\n temp2 = %d\n temp3 = %d\n temp4 = %d\n temp5 = %d\n temp6 = %d\n temp7 = %d\n temp8 = %d\n temp9 = %d\n",
temp1,temp2,temp3,temp4, temp5,temp6,temp7,temp8,temp9);
return 0;
}
//改程序的輸出結(jié)果
//temp1 = 65535
//temp2 = -1
//temp3 = 65535
//temp4 = 65535
//temp5 = -1
//temp6 = -1
//temp7 = -1
//temp8 = 65535
//temp9 = -1;
//根據(jù)結(jié)果也就是說,無符號(hào)符號(hào)數(shù)據(jù)是可以存儲(chǔ)在有符號(hào)型變量?jī)?nèi)存中的,
//而且有例子在內(nèi)存塊長(zhǎng)度一樣時(shí),不用強(qiáng)轉(zhuǎn),直接賦給無符號(hào)變量時(shí)也可行
//上述事實(shí)可以解釋為內(nèi)存塊不變,采用不同的解碼方式解出不同的數(shù)據(jù)
//但是讀出來的時(shí)候要注意,如果有符號(hào)轉(zhuǎn)無符號(hào)一定要強(qiáng)轉(zhuǎn)
//之所以上例unsigned int輸出-1,我并不是很清楚