Сорри, теперь всё работает Ok:
| Код | #include <string>
typedef unsigned char byte; typedef unsigned long ulong;
// Тестовый пример: // // Параметры длиной 17 бит (2 байта плюс 1 бит) // 10001 10101010110011001 11111111111111111 00001111000011110 // HEX: {0x8d, 0x56, 0x67, 0xff, 0xfe, 0x1e, 0x1e} // значения параметров: 87449, 131071, 7710 (HEX: 0x15599, 0x1ffff, 0x1e1e)
// чтение потока битов из буфера "buf", результат - длинное целое (ulong) // отсчет битов - слева направо // отсчет байтов - слева направо (buf[0] - самый левый) // правый бит из потока прижат к правой границе результата ulong ReadBits(int iLeftBit, int nBitCount, byte *buf) { ulong result = 0;
int iRightBit = iLeftBit + nBitCount - 1; int leftBitInByte = iLeftBit % 8; int rightBitInByte = iRightBit % 8; byte leftMask = 0xff>>leftBitInByte; byte rightMask = 0xff<<(7 - rightBitInByte); int iLeftByte = iLeftBit>>3; int iRightByte = iRightBit>>3;
// первый и последний биты - в пределах одного байта if(iLeftByte == iRightByte) { result = (result | buf[iLeftByte] & leftMask & rightMask)>>(7 - rightBitInByte); } else { result = buf[iLeftByte] & leftMask; for(int iByte = iLeftByte+1; iByte < iRightByte; iByte++) result = (result<<8) | buf[iByte]; result = (result<<(rightBitInByte+1)) | ((buf[iRightByte] & rightMask)>>(7 - rightBitInByte)); }
return result; }
// чтение 4-х параметров, возвращает дин. массив параметров типа ulong ulong *ReadParams(byte *buf) { int nEachParamLength = ReadBits(0, 5, buf); int nBytesCnt = ((5 + nEachParamLength*3)>>3) + 1; ulong *params = new ulong[4]; int iBit = 5; for(int iParam = 0; iParam < 4; iParam++, iBit += nEachParamLength) params[iParam] = ReadBits(iBit, nEachParamLength, buf); return params; }
// тестовый пример int main(int argc, char* argv[]) { byte buf[] = {0x8d, 0x56, 0x67, 0xff, 0xfe, 0x1e, 0x1e}; ulong *params = ReadParams(buf);
// ...
delete params; return 0; }
|
ЗЫ, ну и шрифт тут... Пришлось убрать из поста маркеры границ битов... |