0

I have a problem with my code. I want to store numbers from 0 to 127 in bits, but I don't want to waste a number of bits as 0s in the beginning of the number, for some numbers.

For example, storing 15 would take 4 bits. I don't want to waste another 4 bits for putting 0s in the beginning of 1111. In other words, I want to save 00001111 (which makes 15) as only 1111. The problem is that the next number may be in another bit lengths.

How can I save these numbers in the most efficient way without wasting 1 byte for each of them. Imagine I have a series of numbers as follows:

4, 66, 127, 55, 0, 6

I expect the results for numbers 4, 66, 127, 55, 0, 6 to look like:

100 1000010 1111111 110111 0 110

instead of: 00000100 01000010 01111111 00110111 00000000 00000110

And I don't want to specify 1 byte for each. How can I do it? Thanks for any help.

I have read something about bit lengths, and bit fields. But I couldn't understand anything from it.

I expect the results for numbers 4, 66, 127, 55, 0, 6 to look like:

100 1000010 1111111 110111 0 110

instead of: 00000100 01000010 01111111 00110111 00000000 00000110

Cute Boy
  • 1
  • 1
  • You should have a look at [variable length codes](https://en.wikipedia.org/wiki/Variable-length_code). There are actually two problems. 1/ These codes must respect some properties if you want the codes to be decipherable. 2/ If some codes are shorter, some will be larger. If you want to have any gain, you must be able to model your data in order to assign shorter codes to more frequent values. This a classical problem in [lossless compression](https://en.wikipedia.org/wiki/Lossless_compression) – Alain Merigot Feb 15 '19 at 16:07
  • What programming language are you using, if any? – Jacob G. Feb 15 '19 at 16:28
  • Python. If it's not possible to do it on Python, I'm interested to know which programming language should I use for this and how. Thank you. – Cute Boy Feb 15 '19 at 17:33

0 Answers0