简体   繁体   English

ANSI C的位操作库

[英]Bit manipulation library for ANSI C

Does anyone knows a good bit manipulation library for ANSI C? 有谁知道ANSI C的好位操作库? What I basically need, is ability, like in Jovial to set specific bits in a variable, something like 我基本上需要的是能力,就像在Jovial中设置变量中的特定位一样

// 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. 有一个名为bitfile的类似库,但它似乎不支持直接内存操作。 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)? 也许这个库作为更大的库的一部分存在( bzip2gzip是通常的嫌疑人)?

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. 大多数函数只是一个或两个语句,这会使调用库函数的开销比典型的C程序员容忍的要多一些。 :) :)

That said, the always-excellent glib has two of the more complicated bit-oriented functions: g_bit_nth_lsf() and g_bit_nth_msf() . 也就是说,始终出色的glib有两个更复杂的面向位的函数: g_bit_nth_lsf()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. 这些用于查找第一个位集的索引,分别从最低位或最高位进行搜索。

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

也许算法从“FXT”一书(在页面的底部链接)将是有益的。

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 用于在任意位置从一个int复制N位到另一个int的算法

There are several different alternatives provided, with the fastest being the assembly solution by fnieto. 提供了几种不同的替代方案,最快的是fnieto的组装解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM