Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 444
Elazar Leibovich Avatar asked Aug 24 '09 12:08

Elazar Leibovich


4 Answers

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.

like image 157
unwind Avatar answered Sep 29 '22 07:09

unwind


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.

like image 32
GRB Avatar answered Sep 29 '22 06:09

GRB


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
like image 44
hlovdal Avatar answered Sep 29 '22 05:09

hlovdal


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

like image 36
zvrba Avatar answered Sep 29 '22 06:09

zvrba