问题
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;
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
then -12 is
1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 0011
and shifting it 31 bits would make
0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0001
which is 1, not -1, so why do I get -1 when I shift it?
回答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.
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.
回答2:
What about this?
int sign = number < 0;
回答3:
Because you are shifting signed integer. Cast the integer to unsigned:
int sign_bit = ((unsigned int)number) >> 31;
回答4:
You can use cmath library
#include <cmath>
and use it like
std::cout << std::signbit(num);
This function get a float value as input and a bool value as output.
true for negative
false for positive
for instance
std::cout << std::signbit(1);
will give you a 0 as output (false)
but while using this function you have to be careful about zero
std::cout << std::signbit(-0.0); // 512 (true)
std::cout << std::signbit(+0.0); // 0 (false)
The output of this lines are not the same.
To remove this problem you can use:
float x = +0.01;
std::cout << (x >= 0 ? (x == 0 ? 0 : 1) : -1);
which give:
0 for 0
1 for positive
-1 for negative
回答5:
For integers, test number < 0
.
For floating point numbers, you may also want take into account the fact that zero has a sign. That is, there exists a -0.0 which is distinct from +0.0. To distinguish the two, you want to use std::signbit.
回答6:
The >>
operator is performing an arithmetic shift, which retains the sign of the number.
回答7:
bool signbit(double x)
{
return 1.0/x != 1.0/fabs(x);
}
My solution that supports +/-0.
回答8:
You could do the following:
int t1 = -12;
unsigned int t2 = t1;
t2 = t2>>31;
cout<<t2;
This will work fine for all implementations of c++.
回答9:
bool signbit(double x)
{
return (__int64)x & 0x8000000000000000LL != 0LL;
}
bool signbit(float x)
{
return (__int32)x & 0x80000000 != 0;
}
来源:https://stackoverflow.com/questions/3001653/how-can-i-access-the-sign-bit-of-a-number-in-c