Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using bitset container in c++

Tags:

c++

I have a string of 8 char long that contain

8 bytes the hex dump is

is 801000000000000

It means bit 1 and 12 is on.

How can I use bitset feature in c++ and make my life easy.

Thanks

like image 400
user79292 Avatar asked Feb 03 '11 01:02

user79292


1 Answers

To do what? Where's the question? I can't really give a good example of "how it will make your life easier" without a problem to solve. All I can do is show you the very basics of how the class works in application.

Here's a link on its interface. If you want to handle just a simple, constant size set of bits then you can make one easily. If you want one that can grow or shrink look to Boost. Here's a quick example with the standard bitset:

std::bitset<40> imFiveBytesLong;

imFiveBytesLong.set(0, true);

Now it looks like

0000000000000000000000000000000000000001

with the 0th bit set. And you can test to see if the bit is set by asking:

bool isItSet = imFiveBytesLong.test(0);

Or you can count the number of set bits by asking:

std::size_t numSet = imFiveBytesLong.count();

Edit:

To answer your comment below check out the to_ulong method of bitset and one of the constructors of bitset. Putting it together:

int main ()
{
  std::bitset<10> mySet(120ul);          // initialize from unsigned long

  std::cout << mySet.to_uLong();         // print as an unsigned long

  return 0;
}
like image 179
wheaties Avatar answered Sep 22 '22 12:09

wheaties