Bit Manipulation Library for ANSI C

Does anyone know a good bit manipulation library for ANSI C? What I basically need is the ability, as in Jovial , to set certain 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, a similar library is called bitfile , but it does not seem to support direct memory manipulation. It only supports feeding bits to file streams.

It is not difficult to write, but if something is tested, I will not reinvent the wheel.

Perhaps this library exists as part of a larger library ( bzip2, gzipare the usual suspects)?

+5
source share
4

, , ,

N int

, fnieto.

+2

, " "; , , C.:)

, glib : g_bit_nth_lsf() g_bit_nth_msf(), , .

+7

:

#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)          \
)

int a = 0x123;
SETBITS(a, BIN(0,0,0,1, 1,1,1,0));
printf("0x%x", a); // should be 0x13F
+3

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

+2
source

All Articles