public UInt64 Read(int numbits, BitStreamCtx ctx)
{
int offset_r = (int)(ctx.Offset & 31);
int offset_q = (int)(ctx.Offset >> 5);
uint u;
u = this.Buffer [offset_q];
// cases:
// 1) numbits is contained in q-th item
// 2) numbits is in two items, q and q+1 th items
// r is the remainder in the this.Offset bit-stream
// q is the integer number containing the this.Offset bit
// Console.WriteLine("u: {0}, offset_q: {1}, offset_r: {2}, mask: {3}, numbits: {4}",
// u, offset_q, offset_r, mask, numbits);
UInt64 output;
if (numbits + offset_r <= 32) {
// case 1
uint mask = (uint)((1ul << (numbits)) - 1);
output = (u >> offset_r) & mask;
} else {
// case 2
u >>= offset_r;
int d1 = 32 - offset_r;
// int d2 = numbits + offset_r - 32;
int d2 = numbits - d1;
uint v = this.Buffer [offset_q + 1] & ((1u << d2) - 1);
v <<= d1;
output = u | v;
}
ctx.Offset += numbits;
return output;
}