隔离位组的有效且可读的方法
给定偏移量 OFF 和长度 LEN,隔离一组位并将其右移。 (用法:int 保存多个具有给定偏移量和长度的较小范围整数)。例如使用偏移量 4 和长度 4,
a = 110101011000
----^^^^---- this is the group
000000000101
^^^^ isolated and right-shifted here
我目前在
(a>>OFF)&((1<<(LEN+1))-1)
上面的示例中使用给出
a 110101011000
a>>OFF 000011010101
1<<(LEN+1) 000000010000
1<<(LEN+1)-1 000000001111
(a>>OFF)&((1<<(LEN+1))-1) 000000000101
是否有更可读/更有效的方法?
Given offset OFF and length LEN, isolate a group of bits and shift it to the right. (Usage: int holding several smaller-range integers with given offsets and lengths). For example using offset 4 and length 4,
a = 110101011000
----^^^^---- this is the group
000000000101
^^^^ isolated and right-shifted here
I currently use
(a>>OFF)&((1<<(LEN+1))-1)
giving for the example above
a 110101011000
a>>OFF 000011010101
1<<(LEN+1) 000000010000
1<<(LEN+1)-1 000000001111
(a>>OFF)&((1<<(LEN+1))-1) 000000000101
Is there a more readable/efficient way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在这种情况下,没有一个正确的答案。你所做的很好 - 它是正确的,并且通过一些文档它也很清楚。
如果您想要不同的方式,您可以:尝试向左移动
a
,然后再向右移动(假设a
是无符号的 - 否则先转换它);或者您可以首先创建一个掩码(在您的情况下:000011110000),按位与,然后才进行移位。但是,这些不一定比您已有的更漂亮。There isn't a single correct answer in this case. What you did is fine - it's correct, and with some documentation it's also pretty clear.
If you want different ways, you can: try shifting
a
left and then right again (assuminga
is unsigned - otherwise cast it first); or you can first create a mask (in your case: 000011110000), bitwise-and, and only then shift. However, these won't necessarily be prettier than what you already have.110101011000
左移
010110000000
右移
000000000101
这更具可读性..!
110101011000
Shift left
010110000000
Shift right
000000000101
This is more readable..!