NegaFibonacci coding


In mathematics, negaFibonacci coding is a universal code which encodes nonzero integers into binary code words. It is similar to Fibonacci coding, except that it allows both positive and negative integers to be represented. All codes end with "11" and have no "11" before the end.
The Fibonacci code is closely related to negaFibonacci representation, a positional numeral system sometimes used by mathematicians. The negaFibonacci code for a particular nonzero integer is exactly that of the integer's negaFibonacci representation, except with the order of its digits reversed and an additional "1" appended to the end. The negaFibonacci code for all negative numbers has an odd
number of digits, while those of all positive numbers have an even number of digits.

Encoding method

To encode a nonzero integer X:
  1. Calculate the largest encodeable number with N bits by summing the odd negafibonacci numbers from 1 to N.
  2. When it is determined that N bits is just enough to contain X, subtract the Nth negaFibonacci number from X, keeping track of the remainder, and put a one in the Nth bit of the output.
  3. Working downward from the Nth bit to the first one, compare each of the corresponding negaFibonacci numbers to the remainder. Subtract it from the remainder if the absolute value of the difference is less, AND if the next higher bit does not already have a one in it. A one is placed in the appropriate bit if the subtraction is made, or a zero if not.
  4. Put a one in the N+1th bit to finish.
To decode a token in the code, remove the last "1", assign the remaining bits the values 1, −1, 2, −3, 5, −8, 13…, and add the "1" bits.

Table

The code for the integers from −11 to 11 is given below.
numbernegaFibonacci representationnegaFibonacci code
−111010000001011
−101010011001011
−91000100100011
−81000000000011
−71000011000011
−61001000010011
−51001011010011
−4101001011
−3100000011
−2100110011
−110011
00
1111
21000011
31011011
410010010011
510000000011
610001100011
710100001011
810101101011
9100101001010011
10100100000010011
11100100110010011