"Hunter Hou" <hy***@lucent.com> wrote in message
news:cb********@netnews.proxy.lucent.com...
Hello,
I have this very simple program, but it can't be compiled. What's wrong
here?
thanks,
hunter
#include <iostream>
#include <bitset>
int main()
{
std::bitset<6> b1("101010");
std::cout << b1 << std::endl;
return 0;
}
The error is:
bitset.cpp: In function `int main()':
bitset.cpp:8: invalid conversion from `const char*' to `long unsigned int'
bitset.cpp:8: initializing argument 1 of `std::bitset<_Nb>::bitset(long
unsigned int) [with unsigned int _Nb = 6]'
Compiler says can't convert, but bitset<> has such an explicit
constructor.
P.S. > If I use default constructor, everything is fine.
Your compiler is confused, clarify your intentions by first locating the
bitset constructor, if any, that takes a string or char* literal. Its trying
to initialize the bitset container with an unsigned long integer. You could
declare a std::bitset<8> and initialize it with 0x2A or 42 for a binary
sequence of 00101010.
But fortunately, you shouldn't need to, bitset takes a reference to a
std::string as an arguement to one of its constructors:
in <bitset>.... you will find something like this:
explicit bitset(const string& _S, size_t _P = 0, size_t _L = (size_t)(-1))
so try declaring a std::string and initializing it with "101010".
#include <iostream>
#include <bitset>
int main()
{
std::string s1("101010");
std::bitset<6> b1(s1);
std::cout << b1 << std::endl;
return 0;
}
Also:
#include <iostream>
#include <bitset>
int main()
{
std::bitset<8> b1(0x2A); // 00101010
int sz = b1.size();
for (int i = 0; i < sz; i++) // from b1[7] to b1[0]
{
std::cout << b1[sz - i - 1];
}
std::cout << std::endl;
return 0;
}