C++ 将布尔值转换为位序列
我想找一个操作符来代替+?那就行了C++ 将布尔值转换为位序列,c++,boolean,byte,bit,C++,Boolean,Byte,Bit,我想找一个操作符来代替+?那就行了 unsigned char bits = true + false + true + true + true; // 1 byte is sufficient 变成以下位模式: 00010111 那么如何在if中检查该位模式 if (bits == 00010111) 为什么不使用。有一种方法可以设置各种位并转换为无符号长字符。只需对其执行&运算符即可获得字节。为什么不使用。有一种方法可以设置各种位并转换为无符号长字符。只需对其执行一个&运算符即可获得
unsigned char bits = true + false + true + true + true; // 1 byte is sufficient
变成以下位模式:
00010111
那么如何在if中检查该位模式
if (bits == 00010111)
为什么不使用。有一种方法可以设置各种位并转换为无符号长字符。只需对其执行&运算符即可获得字节。为什么不使用。有一种方法可以设置各种位并转换为无符号长字符。只需对其执行一个&运算符即可获得所需的字节。
bits = true << 5 | false << 4 | true << 3 | true << 2 | true << 1;
或
你想要
bits = true << 5 | false << 4 | true << 3 | true << 2 | true << 1;
或
您可以使用的字符串构造函数
#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();
}
不过,有更好的方法可以做到这一点。您可以使用的字符串构造函数
#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();
}
不过有更好的方法可以做到这一点。运算符+需要将当前值左移一位,然后按位或传入的true或false并返回该值 这是我提出的一个快速实现:
#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;
}
对其进行处理运算符+需要将当前值左移一位,然后按位或传入的true或false返回该值 这是我提出的一个快速实现:
#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;
}
第二个问题使用BOOST_BINARY。第二个问题使用BOOST_BINARY。如果出于某种原因,他更喜欢这种语法,那么+可以代替|。您也可以使用^代替+来代替。两者的问题在于,如果应用两次,它们就不是不变的。如果出于某种原因,他更喜欢这种语法,那么+可以代替|。你也可以用^代替+来代替。两者的问题在于,如果应用两次,它们就不是不变的。这是真的啊,是的,但他使用了加法运算符,我不能完全模仿它,除非向后推。我想了想。啊,是的,但他使用了加法运算符,我不能完全模仿它,除非向后推。我想了想。