开发者

two's complement finding algorithm

I am trying to see how compiler writes in binary negative numbers, so here is code which should do it

#include <cstdlib>
#include <iostream>
using namespace std;
void complement(int n)
{
    int l = n;
    int s = 0;
    int k = 0;
    int m = 0;

    while (n != 0)
    {
        s = n  %  2;
        n /= 2;
        cout << s << "  ";
    }

    cout << endl;
    m = ~l + 1;
    cout << m << endl;
    cout << endl;

    while (m != 0)
    {
        int k = m  %  2;
        m /= 2;
        cout << k << "  ";
    }
}

int main(int argc, char *argv[])
{
    int n;
    cin >> n;
    cout << endl;
    complement(n);
    system("PAUSE");
    return EXIT_SUCCESS;
}

but strange is tha开发者_开发百科t, when I enter 5, for instance, which clearly in binary form is 101 in 3 bit, its complement -5 is represented -10-1? This is what my code's output shows me, but I know that is it not correct, because 2's complement of any number is given by reversing its bits, 0 by 1 and vice-versa, and then +1, in case of 5(101), -5 will be (010+1)=(011). Please help me, how to correct my code so that, it could make complement correctly.


If you want to see the bits of number you better use such constructs:

int main(int argc, _TCHAR* argv[])
{
    int i = -10; //my value
    std::string result;
    for (int bit = 0; bit < sizeof(int)*8; ++bit)
    {
       int bit_val = 1 & i;
       result = (bit_val ? "1" : "0") + result;
       i = i >> 1;
    }
    std::cout << result << std::endl;
}


The simplest way to see the bits in C++ is to use std::bitset. It supports iostream output and conversion to/from string. Like this:

#include <stdio.h>      // printf
#include <limits.h>     // CHAR_BIT
#include <bitset>

int main()
{
    int const bitsPerByte   = CHAR_BIT;
    int const bitsPerInt    = sizeof( int )*bitsPerByte;
    int const m             = -10;
    std::bitset<bitsPerInt>     bits( m );

    printf(
        "%d in decimal is %s in %d-bits binary.\n",
        m,
        bits.to_string().c_str(),
        bitsPerInt
        );
}

Output:

-10 in decimal is 11111111111111111111111111110110 in 32-bits binary.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜