分析两小段c++代码 关于unsigned运算的坑
生活随笔
收集整理的這篇文章主要介紹了
分析两小段c++代码 关于unsigned运算的坑
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
代碼1
#include <stdio.h>
#include <iostream>
using namespace std;int main()
{unsigned int a = 2, b = 1;cout << a - b << endl;cout << b - a << endl;cout << hex << b - a << endl;long long long_a = 0xffffffffLL;cout << dec << long_a << endl;return 0;
}
output
1
4294967295
ffffffff
4294967295
分析
為什么第二個輸出會是4294967295,原因是:在計算機中是沒有減法運算的,
1-2 在計算機中為1+(-2)
而1的原碼表示為:
0000001
-2的原碼為:
10000010
-2的反碼為,原碼除去符號位取反然后加1,則為:1111 1111 1111 1111 1111 1111 1111 1101+ 0000 0000 0000 0000 0000 0000 0000 0001= 1111 1111 1111 1111 1111 1111 1111 1110
則1+(-2)=0000 0000 0000 0000 0000 0000 0000 0001
+ 1111 1111 1111 1111 1111 1111 1111 1110
= 1111 1111 1111 1111 1111 1111 1111 1111
而1111 1111 1111 1111 1111 1111 1111 1111的16進制就是:
0xffffffff
10進制是:
4294967295
代碼2
#include <iostream>
using namespace std;
int main() {//unsigned( int 和 unsigned比較的時候,int會先轉(zhuǎn)為unsigned,負(fù)數(shù)注意!)int j = -1;char arr[9] = { 1,2,3,4,5,6,7,8,9 };while (j < sizeof(arr)) {if (j == -1)cout << j << " ";elsecout << arr[j] << " ";j++;}cout << endl;return 0;
}
output
什么都不輸出
分析
發(fā)現(xiàn)結(jié)果什么都沒有,為什么?
因為unsigned( int 和 unsigned比較的時候,int會先轉(zhuǎn)為unsigned,負(fù)數(shù)注意!)
sizeof返回的是unsigned類型
由上一個例子我們可以知道-1在unsigned情況下是:4294967295
所以循環(huán)壓根沒有執(zhí)行
總結(jié)
以上是生活随笔為你收集整理的分析两小段c++代码 关于unsigned运算的坑的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 二叉树的前序、中序、后序非递归遍历 py
- 下一篇: Centos7常用命令