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 17 #define LOG_TAG "AudioSPDIF" 18 //#define LOG_NDEBUG 0 19 20 #include <string.h> 21 #include <assert.h> 22 23 #include <log/log.h> 24 #include "BitFieldParser.h" 25 26 namespace android { 27 BitFieldParser(uint8_t * data)28BitFieldParser::BitFieldParser(uint8_t *data) 29 : mData(data) 30 , mBitCursor(0) 31 { 32 } 33 ~BitFieldParser()34BitFieldParser::~BitFieldParser() 35 { 36 } 37 readBits(uint32_t numBits)38uint32_t BitFieldParser::readBits(uint32_t numBits) 39 { 40 ALOG_ASSERT(numBits <= 32); 41 42 // Extract some bits from the current byte. 43 uint32_t byteCursor = mBitCursor >> 3; // 8 bits per byte 44 uint8_t byte = mData[byteCursor]; 45 46 uint32_t bitsLeftInByte = 8 - (mBitCursor & 7); 47 uint32_t bitsFromByte = (bitsLeftInByte < numBits) ? bitsLeftInByte : numBits; 48 uint32_t result = byte >> (bitsLeftInByte - bitsFromByte); 49 result &= (1 << bitsFromByte) - 1; // mask 50 mBitCursor += bitsFromByte; 51 52 uint32_t bitsRemaining = numBits - bitsFromByte; 53 if (bitsRemaining == 0) { 54 return result; 55 } else { 56 // Use recursion to get remaining bits. 57 return (result << bitsRemaining) | readBits(bitsRemaining); 58 } 59 } 60 61 } // namespace android 62