参考别人的代码,自己修改了一下。发现有符号数和无符号数,如果都是正数的话,二进制值是一样,因此不能简单地和0比较。
有几点值得注意的:
(1)有符号类型和无符号类型一起做运算,有符号类型会自动转成无符号类型;
(2)有符号数最高位是符号位,当有符号数是负数时,转成无符号数,则变成正数,而且一般是很大的正数;
(3)无符号数没有符号位,因此无符号数全部都大于等于0(>=0);
(4)如果一个数是正数,它的有符号和无符号的表示都是一样,只是编译器按照不同的类型解释它。
具体代码,如下:
#include <iostream>
#include <iomanip>
using namespace std;
#define ISUNSIGNED(a) (((a) | 0x1 << (8 * sizeof(a) - 1)) > 0)
#define ISUNSIGNED_TYPE(type) ((type)-1 > 0)
int main()
{
// The values are the same (unsigned vs. signed),
// but types are different by context
int i = 1;
unsigned int ui = 1;
// Set flags
cout.setf(ios::showbase | ios::boolalpha);
// Examples of using macro
cout << ISUNSIGNED(i) << endl;
cout << ISUNSIGNED(ui) << endl;
cout << ISUNSIGNED_TYPE(signed short) << endl;
cout << ISUNSIGNED_TYPE(unsigned short) << endl << endl;
// Tell values by types
cout << (i | 0x1 << ((8 * sizeof(i)) - 1)) << endl;
cout << (ui | 0x1 << ((8 * sizeof(ui)) - 1)) << endl;
cout << (unsigned)-1 << endl;
cout << -1 << endl << endl;
// Tell values ignoring types
cout << hex << (i | 0x1 << ((8 * sizeof(i)) - 1)) << endl;
cout << hex << (ui | 0x1 << ((8 * sizeof(ui)) - 1)) << endl;
cout << hex << (unsigned)-1<< endl;
cout << hex << -1 << endl;
}
输出结果:
false
true
false
true
-2147483647
2147483649
4294967295
-1
0x80000001
0x80000001
0xffffffff
0xffffffff