Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
352 views
in Technique[技术] by (71.8m points)

c++ - in bitset, can i use "to_ulong" for a specific range of bits?

I'm working on something that requires me to get access to specific bits and ranges of bits. I decided to use bitset because it is easy to get access to specific bits; how can I extract a range (subset) of bits?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...