thomas
thomas

Reputation: 161

Using a bitset library

I am doing my first steps with C++ and with some help I have created a code to make an easy function. But I have a problem. I am using a bitset function that needs a specific library and I don't know who to introduce this library in my code.

I have been reading some information in the net but I don't achieve to do it, so I wonder if any of you can tell me in a detailed way how to do it.

So that you make an idea I have been looking in http://www.boost.org/doc/libs/1_36_0/libs/dynamic_bitset/dynamic_bitset.html, http://www.boost.org/doc/libs/1_46_0/libs/dynamic_bitset/dynamic_bitset.html#cons2 and simmilar places.

I attached my code so that you make and idea what I am doing.

Thanks in advance :)

// Program that converts a number from decimal to binary and show the positions where the bit of the number in binary contains 1

#include<iostream>
#include <boost/dynamic_bitset.hpp>
int main() {
unsigned long long dec;
std::cout << "Write a number in decimal: ";
std::cin >> dec;
boost::dynamic_bitset<> bs(64, dec);
std::cout << bs << std::endl;
for(size_t i = 0; i < 64; i++){
    if(bs[i])
        std::cout << "Position " << i << " is 1" << std::endl;
}
//system("pause");
return 0;

}

Upvotes: 0

Views: 1848

Answers (1)

Vijay Mathew
Vijay Mathew

Reputation: 27164

If you don't want your bitset to dynamically grow, you can just use the bitset that comes built-in with all standards compliant C++ implementations:

#include <iostream>
#include <bitset>

int main() {
  unsigned long long dec;
  std::cout << "Write a number in decimal: ";
  std::cin >> dec;
  const size_t number_of_bits = sizeof(dec) * 8;
  std::bitset<number_of_bits> bs(dec);
  std::cout << bs << std::endl;
  for (size_t i = 0; i < number_of_bits; i++) {
    if (bs[i])
      std::cout << "Position " << i << " is 1" << std::endl;
  }
  return 0;
}

To use the dynamic_bitset class, you have to download the Boost libraries and add the boost folder to your compiler's include directories. If you are using the GNU C++ compiler you should something like:

g++ -I path/to/boost_1_46_1 mycode.cpp -o mycode

Upvotes: 1

Related Questions