2

I want to know the good algorithm to get the (-2) based binary bits for the specific number.

So let me define what (-2) based binary bits. The bits is the array of binary element of 1 or 0. The number K represented by this N length bits A is calculated following:

K = A[0] * (-2 ^ 0) + A[1] * (-2 ^ 1) + A[2] * (-2 ^ 2) + ... +  + A[N-1] * (-2 ^ (N-1))

So for example, the bits 00011 represents the number 8 because

1*(-2^4) + 1*(-2^3) + 0*(-2^2) + 0*(-2^1) + 0*(-2^0)

So the question is when the number is defined, what is the good algorithm to calculate shortest bits explained above.

Ralf R
  • 33
  • 5

1 Answers1

4

Wikipedia shows this surprising method:

unsigned int toNegaBinary(unsigned int value) // input in standard binary
{
    unsigned int Schroeppel2 = 0xAAAAAAAA; // = 2/3*((2*2)^16-1) = ...1010
    return (value + Schroeppel2) ^ Schroeppel2; // eXclusive OR
    // resulting unsigned int to be interpreted as string of elements ε {0,1} (bits)
}
Axel Kemper
  • 10,544
  • 2
  • 31
  • 54