如何在C ++中访问数字的符号位? [英] How can I access the sign bit of a number in C++?
问题描述
我希望能够使用C ++访问数字的符号位.我当前的代码如下所示:
I want to be able to access the sign bit of a number in C++. My current code looks something like this:
int sign bit = number >> 31;
这似乎可行,给我0
代表正数,给我-1
代表负数.但是,我看不到如何得到负数的-1
:如果12是
That appears to work, giving me 0
for positive numbers and -1
for negative numbers. However, I don't see how I get -1
for negative numbers: if 12 is
0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 1100
那么-12是
1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 0011
将其移位31位将使
0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0001
它是1,而不是-1,那么为什么在移动它时我得到-1?
which is 1, not -1, so why do I get -1 when I shift it?
推荐答案
在C ++中右移负数的结果是实现定义的.因此,没人知道您的-12
右移应该在特定平台上发生什么.您认为它应该具有以上(1
)的含义,而我说它可以轻松产生全为模式,即-1
.后者称为符号扩展移位.在扩展符号时,符号位被复制到右侧,但从未移出其位置.
The result of right-shifting a negative number in C++ is implementation-defined. So, no one knows what right-shifting your -12
should get on your specific platform. You think it should make the above (1
), while I say that it can easily produce all-ones pattern, which is -1
. The latter is called sign-extended shifting. In sign-extended shifting the sign bit is copied to the right, but never shifted out of its place.
如果您只对符号位的值感兴趣,那么就不要浪费时间尝试使用按位运算,例如移位等.只需将您的数字与0进行比较,看看它是否为负.
If all you are interested in is the value of the sign bit, then stop wasting time trying to use bitwise operations, like shifts etc. Just compare your number to 0 and see whether it is negative or not.
这篇关于如何在C ++中访问数字的符号位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!