gpt4 book ai didi

c - 提取数字中特定位组表示的值

转载 作者:行者123 更新时间:2023-12-02 08:59:47 24 4
gpt4 key购买 nike

如何提取给定数字中特定位组表示的值,即如果位 11,12 和 13 为 1,1,0,则该值应为 6。

最有效的方法是什么?此外,它应该是通用的。我应该能够给出开始和结束位位置,并且应该能够提取由开始和结束位置之间存在的位表示的值。

例如:00000000 00000000 01100000 00011111

对于上面的数字,考虑到第0位是从右端开始,如果我给这个数字,0作为起始位置,2作为结束位置,那么我应该得到值7。

此外,对于上述问题,我们如何处理字节顺序?

最佳答案

six = (value >> 12) & 7;

如果你想通用,

inline unsigned extract_continuous_bits(unsigned value, int start, int end) {
unsigned mask = (~0u) >> (CHAR_BIT*sizeof(value) - end - 1);
return (value & mask) >> start;
}

assert(extract_continuous_bits(0x601f, 12, 14) == 6));
assert(extract_continuous_bits(0x601f, 0, 2) == 7));
assert(extract_continuous_bits(0xf0f0f0f0, 0, 31) == 0xf0f0f0f0));
assert(extract_continuous_bits(0x12345678, 16, 31) == 0x1234));
assert(extract_continuous_bits(0x12345678, 0, 15) == 0x5678));

关于字节顺序,请参阅 When to worry about endianness?

关于c - 提取数字中特定位组表示的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2216646/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com