The following "Increment" method is working perfectly. But I wanted to know is there any faster way to do this in less steps.
public BitArray Increment(BitArray bArray)
{
carry = true;
for (i = 0; i < 32; i++)
{
if (carry)
{
if (bArray[i] == false)
{
bArray[i] = true;
carry = false;
}
else
{
bArray[i] = false;
carry = true;
}
}
}
return bArray;
}
Thanks....
There's one very obvious improvement you can make: stop when you're done!
public void Increment(BitArray bArray)
{
for (int i = 0; i < 32; i++)
{
bool previous = bArray[i];
bArray[i] = !previous;
if (!previous)
{
// Found a clear bit - now that we've set it, we're done
return;
}
}
}
Alternatively, if you're really only got 32 bits (and will only ever have 32 bits), why not just use an int instead? Incrementing that is really easy! You could always wrap it in your own custom struct if you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With