vdr  2.2.0
bitbuffer.c
Go to the documentation of this file.
1 /**********************************************************************
2  *
3  * HDFF firmware command interface library
4  *
5  * Copyright (C) 2011 Andreas Regel
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11 
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16 
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the
19  * Free Software Foundation, Inc.,
20  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21  *
22  *********************************************************************/
23 
24 #include <string.h>
25 
26 #include "bitbuffer.h"
27 
28 void BitBuffer_Init(BitBuffer_t * BitBuffer,
29  uint8_t * Data, uint32_t MaxLength)
30 {
31  memset(Data, 0, MaxLength);
32  BitBuffer->Data = Data;
33  BitBuffer->MaxLength = MaxLength * 8;
34  BitBuffer->BitPos = 0;
35 }
36 
37 void BitBuffer_SetBits(BitBuffer_t * BitBuffer, int NumBits, uint32_t Data)
38 {
39  uint32_t nextBitPos;
40  uint32_t bytePos;
41  uint32_t bitsInByte;
42  int shift;
43 
44  if (NumBits <= 0 || NumBits > 32)
45  return;
46 
47  nextBitPos = BitBuffer->BitPos + NumBits;
48 
49  if (nextBitPos > BitBuffer->MaxLength)
50  return;
51 
52  bytePos = BitBuffer->BitPos / 8;
53  bitsInByte = BitBuffer->BitPos % 8;
54 
55  BitBuffer->Data[bytePos] &= (uint8_t) (0xFF << (8 - bitsInByte));
56  shift = NumBits - (8 - bitsInByte);
57  if (shift > 0)
58  BitBuffer->Data[bytePos] |= (uint8_t) (Data >> shift);
59  else
60  BitBuffer->Data[bytePos] |= (uint8_t) (Data << (-shift));
61  NumBits -= 8 - bitsInByte;
62  bytePos++;
63  while (NumBits > 0)
64  {
65  shift = NumBits - 8;
66  if (shift > 0)
67  BitBuffer->Data[bytePos] = (uint8_t) (Data >> shift);
68  else
69  BitBuffer->Data[bytePos] = (uint8_t) (Data << (-shift));
70  NumBits -= 8;
71  bytePos++;
72  }
73  BitBuffer->BitPos = nextBitPos;
74 }
75 
76 uint32_t BitBuffer_GetByteLength(BitBuffer_t * BitBuffer)
77 {
78  return (BitBuffer->BitPos + 7) / 8;
79 }
void BitBuffer_SetBits(BitBuffer_t *BitBuffer, int NumBits, uint32_t Data)
Definition: bitbuffer.c:37
void BitBuffer_Init(BitBuffer_t *BitBuffer, uint8_t *Data, uint32_t MaxLength)
Definition: bitbuffer.c:28
uint32_t BitPos
Definition: bitbuffer.h:33
uint32_t MaxLength
Definition: bitbuffer.h:32
uint32_t BitBuffer_GetByteLength(BitBuffer_t *BitBuffer)
Definition: bitbuffer.c:76
uint8_t * Data
Definition: bitbuffer.h:31