宏测试一个给定的整数类型是否是用C符号或无符号? [英] Macro to test whether a given integer type is Signed or Unsigned in C?

查看:184
本文介绍了宏测试一个给定的整数类型是否是用C符号或无符号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/64851/macro-to-test-whether-an-integer-type-is-signed-or-unsigned\">Macro测试整数类型是否带符号

要测试给定的整数类型是否带符号,我用下面的宏:

To test whether the given integer type is signed or unsigned, I used the following macro:

#define IS_SIGNED(type) ((type)~0 < 0)

int main()
{

if(IS_SIGNED(char))
    cout<<"The char type is signed"<<endl;

if(IS_SIGNED(unsigned char)) 
    cout<<"The unsigned char type is signed"<<endl; 
}

该方案将使用两个的一补数再presentation实施工作。我们的想法是,当零是一个人的补充的MSB将被设置为1。然后基于该类型铸造,结果将是正或负。

The program will work in implementations which use two's and one's complement number representation. The idea is when the zero is one's complemented the MSB will be set to 1. Then based on the type casting, the result will be either positive or negative.

我想知道你对这个宏定义对于便携性的意见?

I would like to know your views on this macro definition regarding portability?

推荐答案

修正版本:

#define IS_SIGNED(type) ((type)-1 < 0)

最初的版本是只用 0〜作为一个贫穷的方式来写 1 ,但它仅适用在二进制补码实现。 (这也恰好在符号 - 幅度的实施工作,但失败,甚至可以对​​那些补系统崩溃。)

The original version was just using ~0 as a poor way to write -1, but it only works on twos-complement implementations. (It also happens to work on sign-magnitude implementations, but fails and could even crash on ones-complement systems.)

这篇关于宏测试一个给定的整数类型是否是用C符号或无符号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆