如何在C中设置char[1024]的第513位?
最近在一次采访中有人问我如何在 C 中设置 char[1024] 的第 513 位,但我不确定如何解决这个问题。我看到你如何设置,清楚,并切换单个位?,但是如何从如此大的数组中选择该位呢?
I was recently asked in an interview how to set the 513th bit of a char[1024]
in C, but I'm unsure how to approach the problem. I saw How do you set, clear, and toggle a single bit?, but how do I choose the bit from such a large array?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
...对字符大小和所需的字节顺序做出某些假设。
编辑:好的,很好。如果需要,您可以将
8
替换为CHAR_BIT
。...making certain assumptions about character size and desired endianness.
EDIT: Okay, fine. You can replace
8
withCHAR_BIT
if you want.您必须知道机器上字符的宽度(以位为单位)。对于几乎每个人来说,这个数字都是 8。您可以在 C 程序中使用
limits.h
中的常量CHAR_BIT
。然后,您可以进行一些相当简单的数学计算来找到该位的偏移量(取决于您如何计算它们)。从左侧对位进行编号,a[0] 中的 2⁷ 位为位 0,2⁰ 位为位 7,a[1] 中的 2⁷ 位为位 8,这给出:
有许多合理的方法对位进行编号,这里有两个:
您也可以从数组的另一端开始编号(将其视为一个非常大的大端数字)。
You have to know the width of characters (in bits) on your machine. For pretty much everyone, that's 8. You can use the constant
CHAR_BIT
fromlimits.h
in a C program. You can then do some fairly simple math to find the offset of the bit (depending on how you count them).Numbering bits from the left, with the 2⁷ bit in a[0] being bit 0, the 2⁰ bit being bit 7, and the 2⁷ bit in a[1] being bit 8, this gives:
There are many sane ways to number bits, here are two:
You could also number from the other end of the array (treating it as one very large big-endian number).
小优化:
/ 和 % 运算符相当慢,即使在许多现代 cpu 上也是如此,模数稍微慢一些。我会将它们替换为使用位移位(和减法)的等效操作,显然,只有当第二个操作数是 2 的幂时,这种操作才能很好地工作。
x / 8 变为 x >> 3
x % 8 变为 x-((x>>3)<<3)
对于第二个操作,只需重用初始除法的结果即可。
Small optimization:
The / and % operators are rather slow, even on a lot of modern cpus, with modulus being slightly slower. I would replace them with the equivalent operations using bit shifting (and subtraction), which only works nicely when the second operand is a power of two, obviously.
x / 8 becomes x >> 3
x % 8 becomes x-((x>>3)<<3)
for this second operation, just reuse the result from the initial division.
根据所需的顺序(从左到右或从右到左),它可能会改变。但假设每个字节 8 位的一般想法是选择字节为。这被扩展为很多代码行,希望更清楚地显示预期的步骤(或者可能只是混淆了意图):
然后位位置将计算为:
然后设置位(假设目标是将其设置为 1)而不是清除或切换它):
Depending on the desired order (left to right versus right to left), it might change. But the general idea assuming 8 bits per byte would be to choose the byte as. This is expanded into lots of lines of code to hopefully show more clearly the intended steps (or perhaps it just obfuscates the intention):
Then the bit position would be computed as:
Then set the bit (assuming the goal is to set it to 1 as opposed to clear or toggle it):
当你说第 513 个时,你使用索引 0 还是 1 作为第 1 位?如果是前者,您的帖子引用了索引 512 处的位。我认为这个问题是有效的,因为在 C 中的其他地方,第一个索引始终为 0。
顺便说一句
When you say 513th are you using index 0 or 1 for the 1st bit? If it's the former your post refers to the bit at index 512. I think the question is valid since everywhere else in C the first index is always 0.
BTW