views:

577

answers:

4

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)?

+7  A: 

I think is considered "too simple" for a library; most functions would only be a statement or two, which would make the overhead of calling a library function a bit more than typical C programmers tolerate. :)

That said, the always-excellent glib has two of the more complicated bit-oriented functions: g_bit_nth_lsf() and g_bit_nth_msf(). These are used to find the index of the first bit set, searching from the lowest or the highest bit, respectively.

unwind
I just wrote it, and it took 15 lines of tricky code and much more unit tests. It took me quite a few hours to do that, and I don't see any gain with not providing a simple library for that.
Elazar Leibovich
+2  A: 

You will come a long way with the following macros:

#define SETBITS(mem, bits)      (mem) |= (bits)
#define CLEARBITS(mem, bits)    (mem) &= ~(bits)
#define BIN(b7,b6,b5,b4, b3,b2,b1,b0)                      \
(unsigned char)(                                           \
    ((b7)<<7) + ((b6)<<6) + ((b5)<<5) + ((b4)<<4) +        \
    ((b3)<<3) + ((b2)<<2) + ((b1)<<1) + ((b0)<<0)          \
)

Then you can write

int a = 0x123;
SETBITS(a, BIN(0,0,0,1, 1,1,1,0));
printf("0x%x", a); // should be 0x13F
hlovdal
Half a solution. You need a GETBIT macro as well. And a loop. I'll post mine in a few days.
Elazar Leibovich
+1  A: 

Maybe the algorithms from the "FXT" book (link at the bottom of the page) will be useful.

zvrba
+1  A: 

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.

GRB