An approach I've used: count the number of leading 1 bits, say n
. The size of the number is then 2^n bytes (including the leading 1 bits). Take the bits after the first 0 bit as an integer, and add the maximum value (plus one) that can be represented by a number using this encoding in 2^(n-1) bytes.
Thus,
0b00000000 -> 0 = 0b00000000
0b01111111 -> ...
127 = 0b01111111
0b10000000 00000000 -> 128 = 0b1000000000000000
0b10000000 00000001 -> 129 ...
0b10111111 11111111 -> 16511 = 0b1011111111111111
0b11000000 00000000 00000000 00000000 -> 16512 = 0b11000000000000000000000000000000
0b11011111 11111111 11111111 11111111 -> ...
536887423 = 0b11011111111111111111111111111111
536887424 = 0b1110000000000000000000000000000000000000000000000000000000000000
...
1152921505143734399 = 0b1110111111111111111111111111111111111111111111111111111111111111
1152921505143734400 = 0b111100000000000000000000000000000000000000000000 ...
etc.
This scheme allows any non-negative value to be represented in exactly one way.
(Equivalently, used the number of leading 0 bits.)