[英]Extracting the value represented by a particular set of bits in a number
如何提取給定數量的一組特定位表示的值,即如果位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));
有關字節順序,請參閱何時擔心字節順序? 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.