检查整数是否为无符号 [英] to check whether the integer is unsigned

查看:91
本文介绍了检查整数是否为无符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个整数.我要检查该数字是否未签名.如何放置if语句

Let suppose I have a integer. I want to check whether that number is unsigned. How to put if statement

推荐答案

您不能这样做. Signedunsigned只是同一位模式的不同解释,例如,在32位机器上,如果被解释,则位模式0xFFFFFFFF-1 如果被解释为未签名,则为4,294,967,295.
但是,如果知道变量的大小,则可以检查最高有效位,如果它是0,则该变量在signedunsigned解释中表示相同的数字(例如,0x00000001unsigned解释中的0x00000001均为1 ).
You cannot do that. Signed and unsigned are just different interpretations of the same bit pattern, for instance, on a 32 bit machine, the bit pattern 0xFFFFFFFF is -1 if interpreted as signed while is 4,294,967,295 if interpreted as unsigned.
If you know the size of the variable, however, then you may check the most significant bit, if it is 0 then the variable represents the same number both in the signed and unsigned interpretation (e.g. 0x00000001 is 1 both in signed and unsigned interpretation).


1.如果您想知道整数是否为负数(不是``signed''-``signed''是类型的属性,而不是a的属性值!),然后只写
1. If you want to know if an integer value is negative (not ''signed'' - ''signed'' is a property of a type, not a property of a value!), then just write
if (mynumber < 0) {
   puts ("this value is negative");
}



2.如果要确保对特定的类型进行了签名(或未签名),请在声明中使用适当的限定符:



2. If you want to make sure that a particular type is signed (or unsigned), then use the appropriate qualifier in the declaration:

char mychar; // wrong: is it signed or unsigned?
unsigned char myunsigned; // ok, this type is unsigned
signed char mysigned; // ok, this type is signed



3.如果要检查整体模板类型参数以了解它是带符号类型还是无符号类型,请参阅解决方案3

4.如果您不希望上述任何一种,请更加简洁:请在C/C ++术语中指定术语"整数"或"数字'';请在输入"未签名"时验证您使用的是正确的术语.



3. If you want to check an integral template type argument to find out whether it is a signed or unsigned type, see solution 3

4. If you want none of the above, please be more concise: please specify in the terminology of C/C++ what you mean by the terms ''integer'' or ''number''; please verify that you were using the correct term when you said ''unsigned''.


Boost库具有一种用于此目的的特征:

is_unsigned [
Boost library has a type trait just for that:

is_unsigned[^]

By the way, I think your question was badly formulated and Solution 2 (now removed) was probably the answer to your "real" question is you want to know if a number like 18 is unsigned...


这篇关于检查整数是否为无符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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