I have to write individual Bits to a file (for huffman code). To do so I send bits to a function which buffers them until a byte is filled and then returns the byte. I can´t figure out why it doesn’t work, the function outputs wrong bytes (but no errors).
Here is the bitsBuffer function:
// Buffers bits until one byte is filled, the returns it and return code turns positive
int bitsBuffer(char inByte, char nBits, char* outByte, char finish)
{
int i;
static short unsigned buffer = 0;
static char unsigned offset = 0;
// Very readable way to add nBits Bits to buffer
buffer |= (inByte & ~(~0 << nBits)) << offset;
offset += nBits;
if (offset >= 8) {
*outByte = (char)buffer;
buffer >>= 8;
offset -= 8;
return 1;
}
if (finish) {
buffer = 0;
if (offset) {
*outByte = (char)buffer;
offset = 0;
return 1;
}
offset = 0;
return 0;
}
return 0;
}
I use this program to test the bitbuffer (I pipe the output to xxd -b
to view the bits):
#include "bitsHandler.h"
#include <stdio.h>
int main()
{
char a[] = { 0b0110, 0b1, 0b100010, 0b111, 0b100110, 0b0 };
char b[] = { 4, 1, 6, 3, 6, 1 };
char c[100];
int counter = 0;
for (int i = 0; i < 6; i++) {
if (bitsBuffer(a[i], b[i], &c[counter], 0)) {
counter++;
}
}
if (bitsBuffer(0, 0, &c[counter], 1)) {
counter++;
}
fwrite(c, sizeof(char), counter, stdout);
}
I replicated the function on paper (went through every step by hand) and I can’t find my mistake. Help is appreciated.