1

I have numbers lower than 16 and I want to store them the smallest way possible. I currently convert my integer to a byte but I don't need the whole byte. I think I only need 4 bits to hold my number. I want to use as little of a byte as I can.

byte solutionLength = (byte) myArray.length;
return solutionLength;

myArray.length is always less than 12. How can I use as few bits to store to my variable solutionLength ?

ProgrammingCuber
  • 377
  • 4
  • 14

2 Answers2

4

It's impossible to have data types lower than a byte in size. If you have multiple numbers to store you can do a trick: store two 4-bit values in one byte.

byte storage = (byte) (((byte)myArray.length << 4) | (byte)myArray2.length);

Here you store two numbers in one byte. To access them try:

byte myArrayLength = (byte) ((storage & 0xf0) >> 4);
byte myArrayLength2 = (byte) (storage & 0x0f);

But integer would be better solution for it by avoiding type conversions

uakruk
  • 56
  • 1
3

You can use byte array, each byte will hold two values - one in higher 4 bits and another in lower for bits. E.g. 0x1F holds 1 and F. And you need to create a class which will calculate values by index.

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275