fork(4) download
  1. #include <iostream>
  2. #include <cstdint>
  3.  
  4. uint32_t getBits(const void *Data, uint32_t DataLen, uint32_t StartBit, uint8_t NumBits)
  5. {
  6. uint32_t Result = 0;
  7. if (DataLen != 0)
  8. {
  9. const uint8_t *pData = &(static_cast<const uint8_t*>(Data)[StartBit / 8]);
  10. uint8_t b = *pData;
  11. int BitOffset = 7 - (StartBit % 8);
  12. for(int i = 0; i < NumBits; ++i)
  13. {
  14. Result <<= 1;
  15. Result |= ((b >> BitOffset) & 0x01);
  16. if (--BitOffset < 0)
  17. {
  18. b = *(++pData);
  19. BitOffset = 7;
  20. }
  21. }
  22. }
  23. return Result;
  24. }
  25.  
  26. int main() {
  27. uint8_t arr[] = {0x00, 0x00, 0xFF, 0xF1, 0x6D, 0xA2, 0x00, 0x00};
  28. uint32_t value = getBits(arr, 8, 17, 13);
  29. std::cout << value << " (" << std::hex << value << ")";
  30. return 0;
  31. }
Success #stdin #stdout 0s 4520KB
stdin
Standard input is empty
stdout
8188 (1ffc)