I have been trying to find the binary representation of negative numbers. As per my knowledge the negative numbers are stored as a 2's complement in the computer. And, the MSB is 1, indicating that it is negative.
So, I have the following code to print the binary representation of any number::
void printBits(int n) {
if((n >> 1) == 0) {
cout << (n & 1);
return;
}
printBits(n >> 1);
cout << (n & 1);
}
But, it fails for negative numbers, probably because on left shifting the sign bit doesn't get changed, but does get shifted. So, how do i print the binary representation.
There's a function bitset
, which prints the representation like this:
bitset<numberOfBitsRequired>(numberToBeRepresented)
I tried using it on ideone, which is probably a 64-bit compiler.
So, if in the numberOfBitsRequired
, I give the input as 64
, I get this output::
1111111111111111111111111111111111111111111111111111111111111111
But, if I change the numberOfBitsRequired
to 65, I get::
01111111111111111111111111111111111111111111111111111111111111111
From the zero in the starting I can understand the the number of bits have been exceeded. Is there a way that I can find the config of the compiler?? Which I can later use to in my code for finding the bit representation.
Thanks for any help in advance.