检查整数是否为无符号 [英] to check whether the integer is unsigned
问题描述
假设我有一个整数.我要检查该数字是否未签名.如何放置if语句
Let suppose I have a integer. I want to check whether that number is unsigned. How to put if statement
推荐答案
您不能这样做.Signed
和unsigned
只是同一位模式的不同解释,例如,在32
位机器上,如果被解释,则位模式0xFFFFFFFF
为-1
如果被解释为未签名,则为4,294,967,295
.
但是,如果知道变量的大小,则可以检查最高有效位,如果它是0
,则该变量在signed
和unsigned
解释中表示相同的数字(例如,0x00000001
和unsigned
解释中的0x00000001
均为1
).
You cannot do that.Signed
andunsigned
are just different interpretations of the same bit pattern, for instance, on a32
bit machine, the bit pattern0xFFFFFFFF
is-1
if interpreted as signed while is4,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 is0
then the variable represents the same number both in thesigned
andunsigned
interpretation (e.g.0x00000001
is1
both insigned
andunsigned
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屋!