Search code examples
compressionlossless-compression

combining two seperate numbers into a single byte and being able to uncombine them later


I'm not sure this is possible, but perhaps there's something I'm not thinking about. I have two numbers that I want to combine together into a single byte (8 bits). The first number can have 80 different values (0 to 79), and the second number can have 8 different values (0 to 7). I know I can combine them into 9 bits with simple bit shifting and masking, but is there a way to combine them into 8 bits and still be able to uncombine them later without any knowledge of the data already?

Thanks for any insight into this!


Solution

  • No, it is not possible, because 8 times 80 is more than 256. There are more possible sets of the two values than there are values of one byte. So there cannot exist a one-to-one mapping.

    The more basic question might be: is it possible to combine values whose ranges are not powers of two into a single integer. Yes, you can handle the more general case using multiply, divide, and modulo instead of shift left, shift right, and and.

    For example, if you have a set of 15 values (x = 0..14) and a set of 17 values (y = 0..16), then you should be able to stuff them into a byte, since 15 * 17 = 255, which is less than 256. To put them into a byte:

    b = x * 17 + y
    

    To extract them:

    x = b / 17;
    y = b % 17;
    

    This is easily extended to three or more values as well.

    But if it don't fit, it don't fit.