今天一個很偶然的機會,需要回答一個將無符號數據存到有符號變量的問題。我編碼如下,結果很有意思,我是在VC6里調試的,有高人看到可否幫忙指點下。
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;
}
//改程序的輸出結果
//temp1 = 65535
//temp2 = -1
//temp3 = 65535
//temp4 = 65535
//temp5 = -1
//temp6 = -1
//temp7 = -1
//temp8 = 65535
//temp9 = -1;
//根據結果也就是說,無符號符號數據是可以存儲在有符號型變量內存中的,
//而且有例子在內存塊長度一樣時,不用強轉,直接賦給無符號變量時也可行
//上述事實可以解釋為內存塊不變,采用不同的解碼方式解出不同的數據
//但是讀出來的時候要注意,如果有符號轉無符號一定要強轉
//之所以上例unsigned int輸出-1,我并不是很清楚
posted on 2007-10-17 22:46
frank.sunny 閱讀(3006)
評論(13) 編輯 收藏 引用 所屬分類:
C/C++學習和實踐