简体   繁体   中英

How to negate two's complement array

I have an array in c++, in which every element is a digit of a two's complement number (in binary). eg : digits[3] = {1, 1, 0}, which is equal to -2 in decimal. Now, what I have to do is try to convert it into its negative, so in my case {0, 1, 0}, 'cause is 2. I know that a quick way to do it is inverting all the bits and adding one to the result, but how to do it by keeping each element into its own position in the array?

You may call these two functions in sequence.

void invert_array_elements(int* array, size_t array_size) {
    for (size_t ii{0}; ii < array_size; ++ii) {
        array_size[ii] ^= 1; 
    }
}

// Returns true if there is a remaining carry
bool add_one(int* array, size_t array_size) {
    int carry{1};
    for (int ii{array_size - 1}; ii >= 0; --ii) {
        array_size[static_cast<size_t>(ii)] += carry;
        if (array_size[static_cast<size_t>(ii)] > 1) {
            array_size[static_cast<size_t>(ii)] = 0;
            carry = 1;
        } else {
            carry = 0;
        }
    }
    return 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