0

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.

coderzz027
  • 251
  • 2
  • 10
  • If you want to get the real representation used by the computer, I would suggest casting the pointer to `usigned int`. If you want to get some fixed representation not depending on the computer, you should choose the representation and then write a code for it. – Petr Jun 22 '15 at 11:43
  • Probably want to use a C++ idiom like std::bitset. – Robinson Jun 22 '15 at 11:46
  • @Robinson yea, but how does bitset know the configuration of my compiler? Please see d part of the question I just highlighted! – coderzz027 Jun 22 '15 at 19:27

0 Answers0