1

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];
}
progNewbie
  • 4,362
  • 9
  • 48
  • 107
  • 4
    That's because they aren't bits, they're `int`s. If an `int` stores a `0` and you invert all its bits in two's complement, you indeed get `-1`. – Blaze Feb 25 '19 at 13:11
  • 1
    `binary[i] = 1 - binary[i];` might be what you want. – john Feb 25 '19 at 13:44

1 Answers1

2

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 (i.e. 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;
    }
}
rustyx
  • 80,671
  • 25
  • 200
  • 267