The negabinary representation of an integer is its representation in base
(i.e., base
negative 2). It is therefore given by the digits
in
|
(1)
| |||
|
(2)
|
where
is a nonnegative integer and each
is 0 or 1.
Negabinary is a positional numeral system, not a fixed-width encoding layered on binary. Unlike sign-and-magnitude representation, ones' complement, and two's complement, it requires neither a fixed word length nor a sign bit. Every integer has a unique finite negabinary representation using the digits 0 and 1 without a separate minus sign, provided leading zeros are omitted and 0 is represented by the single digit 0.
Conversion of
to negabinary can be done using the Wolfram
Language code
Negabinary[n_Integer] := Module[
{t = (2/3)(4^Floor[Log[4, Abs[n] + 1] + 2] - 1)},
IntegerDigits[BitXor[n + t, t], 2]
]
due to D. Librik (Szudzik). The bitwise XOR portion is originally due to Schroeppel (1972), who used an offset whose binary representation has
the alternating bit pattern
.
The following table gives the negabinary representations for the first few integers (OEIS A039724).
| negabinary | negabinary | ||
| 1 | 1 | 11 | 11111 |
| 2 | 110 | 12 | 11100 |
| 3 | 111 | 13 | 11101 |
| 4 | 100 | 14 | 10010 |
| 5 | 101 | 15 | 10011 |
| 6 | 11010 | 16 | 10000 |
| 7 | 11011 | 17 | 10001 |
| 8 | 11000 | 18 | 10110 |
| 9 | 11001 | 19 | 10111 |
| 10 | 11110 | 20 | 10100 |
If these numbers are interpreted as binary numbers and converted to decimal, their values are 1, 6, 7, 4, 5, 26, 27, 24, 25, 30, 31, 28, 29, 18, 19, 16, ... (OEIS A005351). The numbers having the same representation in binary and negabinary are members of the Moser-de Bruijn sequence, 0, 1, 4, 5, 16, 17, 20, 21, 64, 65, 68, 69, 80, 81, ... (OEIS A000695).