Search code examples
cbit-manipulation

Bit manipulation library for ANSI C


Does anyone knows a good bit manipulation library for ANSI C? What I basically need, is ability, like in Jovial to set specific bits in a variable, something like

// I assume LSB has index of 0
int a = 0x123;
setBits(&a,2,5, 0xFF);
printf("0x%x"); // should be 0x13F

int a = 0x123;
printf("0x%x",getBits(&a,2,5)); // should be 0x4

char a[] = {0xCC, 0xBB};
char b[] = {0x11, 0x12};
copyBits(a,/*to=*/4,b,/*from=*/,4,/*lengthToCopy=*/8);
// Now a == {0x1C, 0xB2}

There's a similar library called bitfile, but it doesn't seem to support direct memory manipulation. It only supports feeding bits to file streams.

It's not hard to write, but if there's something tested - I won't reinvent the wheel.

Maybe this library exists as a part of bigger library (bzip2, gzip are the usual suspects)?


Solution

  • This seems to be the problem I was tackling in my question

    Algorithm for copying N bits at arbitrary position from one int to another

    There are several different alternatives provided, with the fastest being the assembly solution by fnieto.