Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 254
jimmy Avatar asked Feb 01 '10 14:02

jimmy


People also ask

Is Bitset faster than an array of bools?

As bitset stores the same information in compressed manner the operation on bitset are faster than that of array and vector.

How do I convert Bitset to all bits to 1?

bitset::set() is a built-in STL in C++ which sets the bit to a given value at a particular index. If no parameter is passed, it sets all bits to 1. If only a single parameter is passed, it sets the bit at that particular index to 1.

What is the use of count () function in Bitset?

C++ bitset count() function is used to count the number of set bits in the binary representation of a number.

What is Bitset <> in C++?

Bitset is a container in C++ Standard Template Library for dealing with data at the bit level. 1. A bitset stores bits (elements with only two possible values: 0 or 1). We can however get the part of a string by providing positions to bitset constructor (Positions are with respect to string position from left to right)


1 Answers

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;
like image 170
kennytm Avatar answered Sep 30 '22 09:09

kennytm