Detection of negative integers using bit operations
- by Nawaz
One approach to check if a given integer is negative or not, could be this: (using bit operations)
int num_bits = sizeof(int) * 8; //assuming 8 bits per byte!
int sign_bit = given_int & (1 << (num_bits-1)); //sign_bit is either 1 or 0
if ( sign_bit )
{
cout << "given integer is negative"<<endl;
}
else
{
cout << "given integer is positive"<<endl;
}
The problem with this solution is that number of bits per byte couldn't be 8, it could be 9,10, 11 even 16 or 40 bits per byte. Byte doesn't necessarily mean 8 bits! Anyway, this problem can be easily fixed by writing,
//CHAR_BIT is defined in limits.h
int num_bits = sizeof(int) * CHAR_BIT; //no assumption.
It seems fine now. But is it really? Is this Standard conformant? What if the negative integer is not represented as 2's complement? What if it's representation in a binary numeration system that doesn't necessitate only negative integers to have 1 in it's most significant bit?
Can we write such code that will be both portable and standard conformant?
Related topics:
Size of Primitive data types
Why is a boolean 1 byte and not 1 bit of size?