libopenraw
|
00001 /* -*- tab-width:4; c-basic-offset:4 -*- */ 00002 /* 00003 * libopenraw - bititerator.cpp 00004 * 00005 * Copyright (C) 2008 Rafael Avila de Espindola. 00006 * 00007 * This library is free software: you can redistribute it and/or 00008 * modify it under the terms of the GNU Lesser General Public License 00009 * as published by the Free Software Foundation, either version 3 of 00010 * the License, or (at your option) any later version. 00011 * 00012 * This library is distributed in the hope that it will be useful, 00013 * but WITHOUT ANY WARRANTY; without even the implied warranty of 00014 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 00015 * Lesser General Public License for more details. 00016 * 00017 * You should have received a copy of the GNU Lesser General Public 00018 * License along with this library. If not, see 00019 * <http://www.gnu.org/licenses/>. 00020 */ 00021 00022 #include <assert.h> 00023 #include "bititerator.h" 00024 00025 namespace OpenRaw { 00026 namespace Internals { 00027 00028 BitIterator::BitIterator(const void * const p) : 00029 m_p(static_cast<const uint8_t * const>(p)), 00030 m_bitBuffer(0), m_bitsOnBuffer(0) 00031 00032 { 00033 } 00034 00035 void BitIterator::load(size_t numBits) 00036 { 00037 size_t numBytes = (numBits + 7) / 8; 00038 00039 //align the bits on the right 00040 m_bitBuffer >>= (32 - m_bitsOnBuffer); 00041 00042 m_bitsOnBuffer += 8 * numBytes; 00043 00044 //load the new bits from the right 00045 for (size_t i = 0; i < numBytes; ++i) { 00046 m_bitBuffer = (m_bitBuffer << 8) | *m_p; 00047 ++m_p; 00048 } 00049 00050 //align the bits on the left 00051 m_bitBuffer = m_bitBuffer << (32 - m_bitsOnBuffer); 00052 } 00053 00054 uint32_t BitIterator::get(size_t n) 00055 { 00056 assert(n <= 25); 00057 00058 if (n == 0) 00059 return 0; 00060 00061 if (n > m_bitsOnBuffer) 00062 load(n - m_bitsOnBuffer); 00063 00064 assert(n <= m_bitsOnBuffer); 00065 00066 uint32_t ret = m_bitBuffer >> (32 - n); 00067 m_bitsOnBuffer -= n; 00068 m_bitBuffer <<= n; 00069 00070 return ret; 00071 } 00072 00073 } 00074 }