C-FAQ 中位数组实现的解释
我正在阅读 C-FAQ 问题编号:20.8,它基本上处理位数组:
http://c -faq.com/misc/bitsets.html
定义的宏之一看起来像这样:
#define BITNSLOTS(nb) ((nb + CHAR_BIT - 1) / CHAR_BIT)
Is this macro旨在计算 char 数组中的元素(或槽)数量(每个槽 = 8 位)?我不确定这个宏在做什么,特别是“+CHAR_BIT -1/CHAR_BIT”的目的是什么。任何线索将不胜感激!
I was reading the C-FAQ question no: 20.8 which basically deals with bit arrays:
http://c-faq.com/misc/bitsets.html
One of the macros defined looks something like:
#define BITNSLOTS(nb) ((nb + CHAR_BIT - 1) / CHAR_BIT)
Is this macro meant to calculate the num of elements(or slots) in the char array (each slot = 8 bits) ? I am not sure what this macro is doing, in particular what the purpose of "+CHAR_BIT -1/CHAR_BIT" is. Any clues will be appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,它计算需要多少个字符来保存这些位。添加的内容是为了使其四舍五入。
Yes, it calculates how many
char
s are needed to hold the bits. The addition stuff is to make it round up.如果 nb 小于 CHAR_BIT,您仍然需要至少一个字符。
If nb is smaller than CHAR_BIT, you'll still need at least one character.
请记住除法是整数除法:没有“...和八分之三”。假设您想要分组为大小为 6 的槽(是的...我知道
CHAR_BIT
是 8 或更多)(1 + 6 - 1) / 6 == (6 / 6) == 1
(5 + 6 - 1) / 6 == (10/6) == 1
(6 + 6 - 1) / 6 == (11 / 6) == 1
(7 + 6 - 1) / 6 == (12 / 6) == 2
Remember the division is integer division: there's no "... and three eighths". Suppose you want to group into slots of size 6 (yeah ... I know
CHAR_BIT
is 8 or more)(1 + 6 - 1) / 6 == (6 / 6) == 1
(5 + 6 - 1) / 6 == (10/6) == 1
(6 + 6 - 1) / 6 == (11 / 6) == 1
(7 + 6 - 1) / 6 == (12 / 6) == 2