in bitset, can i use “to_ulong” for a specific ran

2019-01-19 11:38发布

hi im working on something that demands me to get access to specific/range of bits. i decided to use bitset because it is easy to get access to specific bits but can i extract a whole range of bits?

1条回答
在下西门庆
2楼-- · 2019-01-19 12:35

Method A:

return (the_bitset >> start_bit).to_ulong();

Method B (faster than method A by 100 times on my machine):

unsigned long mask = 1;
unsigned long result = 0;
for (size_t i = start_bit; i < end_bit; ++ i) {
    if (the_bitset.test(i))
       result |= mask;
    mask <<= 1;
}
return result;
查看更多
登录 后发表回答