BitFieldParser.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /*
  2. * Copyright 2015, The Android Open Source Project
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #define LOG_TAG "AudioSPDIF"
  17. //#define LOG_NDEBUG 0
  18. #include <string.h>
  19. #include <assert.h>
  20. #include <log/log.h>
  21. #include "BitFieldParser.h"
  22. namespace android {
  23. BitFieldParser::BitFieldParser(uint8_t *data)
  24. : mData(data)
  25. , mBitCursor(0)
  26. {
  27. }
  28. BitFieldParser::~BitFieldParser()
  29. {
  30. }
  31. uint32_t BitFieldParser::readBits(uint32_t numBits)
  32. {
  33. ALOG_ASSERT(numBits <= 32);
  34. // Extract some bits from the current byte.
  35. uint32_t byteCursor = mBitCursor >> 3; // 8 bits per byte
  36. uint8_t byte = mData[byteCursor];
  37. uint32_t bitsLeftInByte = 8 - (mBitCursor & 7);
  38. uint32_t bitsFromByte = (bitsLeftInByte < numBits) ? bitsLeftInByte : numBits;
  39. uint32_t result = byte >> (bitsLeftInByte - bitsFromByte);
  40. result &= (1 << bitsFromByte) - 1; // mask
  41. mBitCursor += bitsFromByte;
  42. uint32_t bitsRemaining = numBits - bitsFromByte;
  43. if (bitsRemaining == 0) {
  44. return result;
  45. } else {
  46. // Use recursion to get remaining bits.
  47. return (result << bitsRemaining) | readBits(bitsRemaining);
  48. }
  49. }
  50. } // namespace android