有符號整數、無符號整數的轉換以及小資料轉換為大資料
阿新 • • 發佈:2019-01-10
1.有符號轉換為無符號的整數的規則:
unsigned int MySystem::T2U(int x)
{
if (x >= 0)
{
return x;
}
return UINT_MAX + 1 + x;
}
2.無符號轉換為有符號的規則:
<pre name="code" class="cpp">int MySystem::U2T(unsigned int x)
{
if (x<=INT_MAX)
{
return x;
}
return x - (UINT_MAX + 1);
}
3.小資料轉換為大資料的規則:
例如:要將一個無符號數轉換為一個更大的資料型別,我們只要簡單地在表示的開頭新增0,這種運算叫做零擴充套件。 要將一個有符號的轉換為一個更大的資料型別,我們需要在前面新增有效位,這種運算叫做符號擴充套件。
<pre name="code" class="cpp">1)對於無符號的資料-------------------------------------------
<span style="white-space:pre"> </span>unsigned short x = 182; unsigned char *p = (unsigned char*)&x; for (int i = 0;i<sizeof(unsigned short);++i) { cout << hex << int(p[i]) << '\t'; }
編者自己處理器是小端的,所以輸出 0XB6 0X00
如果將其轉換為大的資料型別(unsigned int)。
<pre name="code" class="cpp"><span style="white-space:pre"> </span>unsigned short x = 182; unsigned int x1 = x; unsigned char *p = (unsigned char*)&x1; for (int i = 0;i<sizeof(unsigned);++i) { cout << hex << int(p[i]) << '\t'; }
輸出的結果為: 0XB6 0X00 0X00 0X00
那麼僅僅是在前面新增0.
2)對於無符號的資料---------------------------------------------
<pre name="code" class="cpp">1.對於正數
<span style="white-space:pre"> </span>short x = 182;
int x1 = x;
unsigned char *p = (unsigned char*)&x;
for (int i = 0;i<sizeof(short);++i)
{
cout << hex << int(p[i]) << '\t';
}
輸出的結果為: 0XB6 0X00
將其轉換為大的資料型別:
那麼輸出的結果為: 0XB6 0X00 0X00 0X00
因為前導為0,那麼在前面新增0.
2.對於負數
<pre name="code" class="cpp"><span style="white-space:pre"> </span>short x = -182;
int x1 = x;
unsigned char *p = (unsigned char*)&x;
for (int i = 0;i<sizeof(short);++i)
{
cout << hex << int(p[i]) << '\t';
}
輸出的結果為:0X4A 0XFF
將其轉換為大的資料型別:
那麼輸出的結果為: 0X4A 0XFF 0XFF 0XFF
因為前導為1,那麼在前面新增1