views:

407

answers:

3

I've decided to do it this way

  • flip numbers 0=1, 1=0
  • add 1 to LSB
  • if carry, loop until array[i]==0

But I'm stuck on the last point; how can I say that in a conditional loop?

A: 

So you you store your number as an array of ints, which represent bits. In the code example you attached you forgot to increment the i variable, and to check if it exceeded the size of your array.

You could write something like this (I assume the size of the array is 5):

for (i = 0; i < 5; i++)
{
    if (array1[i] == 1)
        array1[i] = 0;
    else // we found a 0
        array1[i] = 1;
        break;
}
Adam
A: 

I'm not quite sure what you're doing, but maybe this will help:

#define countof(x) (sizeof(x) / sizeof(x[0]))

// an 8-bit number
int byte[8] = {0, 1, 1, 0, 1, 1, 1, 0}; // 1 = on, 0 = off

// flip all bits
for (size_t i = 0; i < countof(byte); ++i)
{
    byte[i] = !byte[i];
}

// add one
for (size_t i = 0; i < countof(byte); ++i)
{
    if (byte[i]) // if on
    {
        byte[i] = 0; // "add 1, reset to zero", and carry (no break)
    }
    else // if off
    {
        byte[i] = 1; // turn on
        break; // nothing to carry, stop adding
    }

}

(I don't know how to push you in the right direction without just explaining the code, sorry. I think you're close enough this is still helpful.)

You see, when you add one, if the bit is already one, reset it to zero, and continue along the bits. If the bit is zero, set it to one, then break out of the loop. (Nothing to carry, so we're done adding.)

Hope that helps. By the way, you'll note the bits are being stored "backwards" in the code above. The LSB is at index 0.

GMan
+1  A: 

You are talking about extended arithmetic. Most processors have carry-out and overflow results from every addition operation, but C does not provide access to them.

Your problem is that numbers get longer as they get bigger. If you're at the last bit you have, and you need to carry out, you need another bit! That means you need to reallocate the array of bits (if you are using an array).

Of course, a more practical solution is to use native integers rather than individual bits, since your processor already handles two's-complement quite nicely. Then, you know that adding one results in a carry-out if the original number is equal to (unsigned) -1. The fundamental problem remains; if you need to carry out of the last unsigned you need to allocate another.

Potatoswatter