2

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)));
    }
}
4

1 回答 1

4

这样的事情应该这样做:

public class FiveBit {

  private byte[] _data;

  public FiveBit(int len) {
    _data = new byte[(len * 5 + 7) / 8];
  }

  public int this[int index] {
    get {
      int i = index * 5 / 8;
      int ofs = index * 5 % 8;
      if (ofs > 3) {
        return ((_data[i] + _data[i + 1] * 256) >> ofs) & 31;
      } else {
        return (_data[i] >> ofs) & 31;
      }
    }
    set {
      int i = index * 5 / 8;
      int ofs = index * 5 % 8;
      int mask = 31 << ofs;
      _data[i] = (byte)((_data[i] & ~mask) | (value << ofs));
      if (ofs > 3) {
        _data[i + 1] = (byte)((_data[i + 1] & ~(mask >> 8)) | (value >> (8 - ofs)));
      }
    }
  }

}

注意:这没有经过彻底测试,但我已经测试过我可以在其中放入 128 个随机 5 位值,并再次获得相同的值。您还应该对参数添加一些范围检查以使代码更加健壮,并且我没有过多考虑类名,因此您肯定可以编造一些更好地描述它的东西。

于 2015-04-12T20:15:07.940 回答