Reputation: 65996
Looking for some operator (I'm guessing in place of + ?) that will do
unsigned char bits = true + false + true + true + true; // 1 byte is sufficient
to become to following bit pattern:
00010111
Then how can I check that bit pattern in an if
if (bits == 00010111)
Upvotes: 1
Views: 130
Reputation: 21317
You can use std::bitset
's string constructor.
#include <bitset>
#include <string>
#include <iostream>
int main() {
std::string bits;
bits.push_back('1');
bits.push_back('0');
bits.push_back('1');
bits.push_back('1');
bits.push_back('1');
std::bitset<8> bitset(bits);
std::cout << bitset.to_string();
}
There are better ways of doing this though.
Upvotes: 3
Reputation: 6771
The operator + would need to do a shift left by one bit of the current value, then "bitwise OR" the incoming true or false and return that.
This is a quickie implementation I came up with:
#include <iostream>
class Foo
{
int result;
public:
Foo() : result(0) {}
Foo(bool value) : result(value ? 1 : 0) {}
explicit Foo(int value) : result(value) {}
Foo operator+(bool value) const
{
std::cout << "adding " << value << std::endl;
return Foo((result << 1) | (value ? 1 : 0));
}
int get_result() const { return result; }
};
int main()
{
Foo x;
x = Foo(true) + false + true;
std::cout << x.get_result() << std::endl;
}
Play around with it here
Upvotes: 2
Reputation: 6882
you want
bits = true << 5 | false << 4 | true << 3 | true << 2 | true << 1;
or
bits |= true;
bits <<= 1;
bits |= false;
bits <<= 1;
bits |= true;
bits <<= 1;
bits |= true;
bits <<= 1;
bits |= true;
Upvotes: 6