1) Transformation from array to integer
Let B = [1 0 0 1 1], where each B[i] corresponds to the power i, from i = 0 (lower) to i = N-1 (upper).
Then, the resulting integer is
[LATEX]X = 1\cdot (-2)^0+0\cdot (-2)^1+0\cdot (-2)^2+1\cdot (-2)^3+1\cdot (-2)^4 = 1 - 8 + 16 = 9[/LATEX]
2) Transformation from integer to array
This direction is a bit more difficult.
First, let us define the floor integer division: C = floor (A/B), where A, B and C are integers.
Let D be the result of usual division A by B, i.e. D = A:B
If D has a fractional part, then C is the nearest left integer to this result. If there is no fractional part, then C = D.
The remainder is defined by absolute values, R = |A| % |B|.
For example
A = 4, B = 3, C = floor (4/3) = 1, R = 1
A = -8, B = 3, C = floor (-8/3) = -3 (Attention !, -3 is left, -2 is right), R = 2
A = -10, B = 5, C = -2, R = 0
In case of negative base, we
1) Consider F = -X
2) Use the usual procedure to obtain the array
i = -1;
while (F != 0)
{
B[++i] = |F| %2;
F = floor (F / -2);
}
3) Since the array goes from lower to upper power, no reverse is necessary.
Let us apply this algo to X = 9
F = -9
|-9| %2 = ----------------------------->1
floor(-9/-2) = 4
|4| % 2 = ---------------------------->0
floor (4/-2) = -2
|-2| %2 = ---------------------------->0
floor (-2/-2) = 1
|1| % 2 = ----------------------------->1
floor (1 / -2) = -1
|-1| % 2 = ---------------------------->1
floor (-1 / -2) = 0 END.
Thus, we obtain B = [1 0 0 1 1], which is right.
Another Example
1) B = [0 0 1 1 1 0 1]. Find X
X = 4 - 8 + 16 + 64 = 76
2) X = 76. Find B
F = -76
|-76| %2 = ----------------------------->0
floor(-76/-2) = 38
|38| % 2 = ---------------------------->0
floor (38/-2) = -19
|-19| %2 = ---------------------------->1
floor (-19/-2) = 9
|9| % 2 = ----------------------------->1
floor (9 / -2) = -5
|-5| % 2 = ---------------------------->1
floor (-5/-2) = 2
|2| % 2 = ----------------------------->0
floor (2 / -2) = -1
|-1| % 2 = ---------------------------->1
floor (-1 / -2) = 0 END.
B = [0 0 1 1 1 0 1]
|