Pregunta

I'm interested in making a class to store data in a more pact manor and I know I can store numbers between 0 and 2^(x)-1 with ease, along with booleans by using bitwise operators, but I'm interested in more odd numbers like a max of 6 or something. I've been fiddling with it in my mind for about a week now and have been googling for about an hour now but I can't really find anything of help.

I'm looking for an algorithm or something to help me figure out how best to pack data that is between 0 and a random number that's between 1 and 32ish...

I'm just brain storming on this and would like to also know if compression like this should even be looked at. one of the reasons why I'm looking into this is for huge arrays and such. Sorry if this is a stupid question, my brain hasn't been very sharp recently.

Also, an example of max values: 1,5,8,3,12,19

A finalized class I was thinking of would be something like:

public class MyObject{
  private long packed;
  ...
  public int getA(){...}
  public void setA(){...}
  public int getB(){...}
  public void setB(){...}

Thanks for the help, ~vzybilly~

¿Fue útil?

Solución

As a general question it's not very interesting to a programmer - maybe to a mathematician/information theorist. Specific examples are fun to play with but not important in today's world where memory is plentiful but all the other work you and computer do is more scarce.

Let's say you had to store a sequence of a lot numbers in the range 1-6. You can fit 12 of these in a 32-bit integer, as 6^12 < 2^32. But now you have extra arithmetic whenever you access data, basically seeing how many 6^n's there are in the entry modulus 6^n+1. This is because there are tradeoffs in speed and compactness for whichever representation you use. "Best" in practice means straightforward.

It's not to say there aren't times when saving space is free, good, and elegant, however it is an issue that should only be asked by one who already has the skills to solve it, in a situation that requires it.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top