vdr  1.7.27
bitbuffer.c
Go to the documentation of this file.
00001 /**********************************************************************
00002  *
00003  * HDFF firmware command interface library
00004  *
00005  * Copyright (C) 2011  Andreas Regel
00006  *
00007  * This program is free software; you can redistribute it and/or
00008  * modify it under the terms of the GNU General Public License
00009  * as published by the Free Software Foundation; either version 2
00010  * of the License, or (at your option) any later version.
00011 
00012  * This program 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
00015  * GNU General Public License for more details.
00016 
00017  * You should have received a copy of the GNU General Public License
00018  * along with this program; if not, write to the
00019  * Free Software Foundation, Inc.,
00020  * 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
00021  *
00022  *********************************************************************/
00023 
00024 #include <string.h>
00025 
00026 #include "bitbuffer.h"
00027 
00028 void BitBuffer_Init(BitBuffer_t * BitBuffer,
00029                     uint8_t * Data, uint32_t MaxLength)
00030 {
00031     memset(Data, 0, MaxLength);
00032     BitBuffer->Data = Data;
00033     BitBuffer->MaxLength = MaxLength * 8;
00034     BitBuffer->BitPos = 0;
00035 }
00036 
00037 void BitBuffer_SetBits(BitBuffer_t * BitBuffer, int NumBits, uint32_t Data)
00038 {
00039     uint32_t nextBitPos;
00040     uint32_t bytePos;
00041     uint32_t bitsInByte;
00042     int shift;
00043 
00044     if (NumBits <= 0 || NumBits > 32)
00045         return;
00046 
00047     nextBitPos = BitBuffer->BitPos + NumBits;
00048 
00049     if (nextBitPos > BitBuffer->MaxLength)
00050         return;
00051 
00052     bytePos = BitBuffer->BitPos / 8;
00053     bitsInByte = BitBuffer->BitPos % 8;
00054 
00055     BitBuffer->Data[bytePos] &= (uint8_t) (0xFF << (8 - bitsInByte));
00056     shift = NumBits - (8 - bitsInByte);
00057     if (shift > 0)
00058         BitBuffer->Data[bytePos] |= (uint8_t) (Data >> shift);
00059     else
00060         BitBuffer->Data[bytePos] |= (uint8_t) (Data << (-shift));
00061     NumBits -= 8 - bitsInByte;
00062     bytePos++;
00063     while (NumBits > 0)
00064     {
00065         shift = NumBits - 8;
00066         if (shift > 0)
00067             BitBuffer->Data[bytePos] = (uint8_t) (Data >> shift);
00068         else
00069             BitBuffer->Data[bytePos] = (uint8_t) (Data << (-shift));
00070         NumBits -= 8;
00071         bytePos++;
00072     }
00073     BitBuffer->BitPos = nextBitPos;
00074 }
00075 
00076 uint32_t BitBuffer_GetByteLength(BitBuffer_t * BitBuffer)
00077 {
00078     return (BitBuffer->BitPos + 7) / 8;
00079 }