简体   繁体   中英

Decimal to Binary with two complement

I tried to convert decimal to binary like this: I got input int and a binary int.

int rem;
int bin[32] = {0};

for(int i=0; input != 0; i++) { //making array of binary, but reversed
    rem = input%2;
    bin[i] = abs(rem);
    input = input / 2;
}

for(int i = 0; i < 32; i++) { //reversed binary is put in correct order
    binary[i] = bin[31 - i];
}

now I want that if the input is negative like "-5" it gives me the two-complement.

When trying to complement every bit with "~", they turn to "-1" somehow.

for (int i = 0; i < 32; i++) {
    binary[i] = ~binary[i];
}

You're almost there.

You store one bit per int , so you need to flip only that bit with for example ^ 1 (XOR 1). That way 0 becomes 1 and 1 becomes 0. The tilde operator ~ will flip all the bits, so 0 becomes -1, and 1 becomes -2 (ie not what you want).

Then, to negate a two's complement number, you need to

  1. invert it
  2. add 1 ( why )

For example:

for (int i = 0; i < 32; i++) {
    binary[i] ^= 1;
}

for (int i = 31; i >= 0; i--) {
    binary[i] ^= 1;
    if (binary[i])
        break;
}

Or combine the two steps into one:

for (int i = 31, carry = 0; i >= 0; i--) {
    if (carry || !binary[i]) {
        binary[i] ^= 1;
        carry = 1;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM