I'm trying to extend this topic a bit by expanding it to cover 5-bit values packed into a byte[] data structure.
The specific objective I'm trying to achieve would be to store a total of 128 5-bit (0-31) numeric values in a 80-byte array with a get/set function to access and manipulate the values within the array.
Does anyone have experience with this?
Edit:
Thanks to Guffa in the accepted answer below, here's an inline version of his class for use in static calls:
byte Get_5_In_BA(ref byte[] storage, int index)
{
int bigIndex = (index * 5) / 8;
int smallIndex = (index * 5) % 8;
if (smallIndex > 3)
{
return ((byte) (((storage[bigIndex] + (storage[bigIndex + 1] * 0x0100)) >> smallIndex) & 0x1F));
}
return ((byte) ((storage[bigIndex] >> smallIndex) & 0x1F));
}
void Set_5_In_BA(ref byte[] storage, int index, byte value)
{
if (value > 31) { value = 31; }
int bigIndex = (index * 5) / 8;
int smallIndex = (index * 5) % 8;
int mask = 0x1F << smallIndex;
storage[bigIndex] = (byte) ((storage[bigIndex] & ~mask) | (value << smallIndex));
if (smallIndex > 3)
{
storage[bigIndex + 1] = (byte) ((storage[bigIndex + 1] & ~(mask >> 8)) | (value >> (8 - smallIndex)));
}
}