判断有符号和无符号的变量或类型[C/C++]

判断有符号和无符号的变量或类型[C/C++]

 

        参考别人的代码,自己修改了一下。发现有符号数和无符号数,如果都是正数的话,二进制值是一样,因此不能简单地和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

参考资料:

1、http://zebras.diandian.com/post/2012-10-24/40041214058

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值