开发者

How to get ones' complement

I need to find ones' complement of a decimal number given as an input. First I convert the decimal number to a binary number using the following code,

int decNum = int.Parse(Console.ReadLine());
string binRep = " ";
int digi = 0;
do
{
    digi = decNum % 2;
    binRep = digi.ToString() + binRep;
    decNum = decNum / 2;
} while (decNum >= 1);
Console.WriteLine(binRep);

then when I do this,

int onesComplement= ~(int.parse(binRep)),

I get weird answers, for example when I give 8 as the input I get 1000 as the binary number but after using the tilde(~) for getting ones' complement I get -1001. I would like开发者_StackOverflow社区 to know what am I missing here, and what best should I do to get ones' complement correctly?


By default the integer is parsed as if it is base 10, and you didn't specify a different base - int.Parse() doesn't offer this. You can use Convert.ToInt32() instead and specify the base the number is based on, in your case 2.

Converts the string representation of a number in a specified base to an equivalent 32-bit signed integer.

So use

int onesComplement= ~Convert.ToInt32(binRep, 2);

Your program can also be shortened to:

int decNum = int.Parse(Console.ReadLine());
string binRep = Convert.ToString(decNum, 2);
Console.WriteLine(binRep);
int onesComplement = ~Convert.ToInt32(binRep, 2);

or even shorter if you don't need to print the binary output:

int decNum = int.Parse(Console.ReadLine());
int onesComplement = ~decNum;


You're getting the weird numbers because when you do int.Parse() it is using base 10, so rather than 1000b it reads that as the literal base 10 integer 1,000. Int32.Parse does not support binary numbers.

To get around this you could perform the bitwise complement using ~ on the original number and print those binary digits.

Here is a slight modification of your code to return the binary representation of a 32bit number, optionally inverting it:

static string GetBinary(string number, bool invert)
{
    // use unsigned ints to avoid negative number problems
    uint decNum = UInt32.Parse(number);
    if (invert) decNum = ~decNum;

    string binRep = String.Empty;
    uint digi = 0;
    do
    {
        digi = decNum % 2;
        binRep = digi.ToString() + binRep;
        decNum = decNum / 2;
    } while (decNum >= 1);

    return binRep;
}


int.Parse thinks your string represents a decimal number (1000).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜