二进制文字?

在代码中,有时我会看到人们以十六进制格式指定常量,如下所示:


const int has_nukes        = 0x0001;

const int has_bio_weapons  = 0x0002;

const int has_chem_weapons = 0x0004;

// ...

int arsenal = has_nukes | has_bio_weapons | has_chem_weapons; // all of them

if(arsenal &= has_bio_weapons){

  std::cout << "BIO!!"

}

但是在这里使用十六进制格式对我来说没有意义。有没有一种方法可以直接用二进制文件呢?像这样:


const int has_nukes        = 0b00000000000000000000000000000001;

const int has_bio_weapons  = 0b00000000000000000000000000000010;

const int has_chem_weapons = 0b00000000000000000000000000000100;

// ...

我知道C / C ++编译器不会对此进行编译,但是必须有解决方法吗?是否可以使用其他语言(例如Java)?


料青山看我应如是
浏览 544回答 3
3回答

杨__羊羊

我会使用一个移位运算符:const int has_nukes&nbsp; &nbsp; &nbsp; &nbsp; = 1<<0;const int has_bio_weapons&nbsp; = 1<<1;const int has_chem_weapons = 1<<2;// ...int dangerous_mask = has_nukes | has_bio_weapons | has_chem_weapons;bool is_dangerous = (country->flags & dangerous_mask) == dangerous_mask;它甚至比泛滥的0更好。

阿晨1998

在C ++ 14中,您将能够使用具有以下语法的二进制文字:0b010101010 /* more zeros and ones */此功能已在最新版本clang和中实现gcc。如果使用options运行那些编译器,则可以尝试一下-std=c++1y。

红糖糍粑

顺便说一下,下一个C ++版本将支持用户定义的文字。它们已经包含在工作草案中。这允许出现这种情况(希望我没有太多错误):template<char... digits>constexpr int operator "" _b() {&nbsp; &nbsp; return conv2bin<digits...>::value;}int main() {&nbsp; &nbsp; int const v = 110110110_b;}conv2bin 将是这样的模板:template<char... digits>struct conv2bin;template<char high, char... digits>struct conv2bin<high, digits...> {&nbsp; &nbsp; static_assert(high == '0' || high == '1', "no bin num!");&nbsp; &nbsp; static int const value = (high - '0') * (1 << sizeof...(digits)) +&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;conv2bin<digits...>::value;};template<char high>struct conv2bin<high> {&nbsp; &nbsp; static_assert(high == '0' || high == '1', "no bin num!");&nbsp; &nbsp; static int const value = (high - '0');};好吧,由于上面的“ constexpr”,我们得到的是在编译时已经完全评估过的二进制文字。上面使用了硬编码的int返回类型。我认为甚至可以使它取决于二进制字符串的长度。它对任何有兴趣的人使用以下功能:广义常数表达式。可变参数模板。可以在这里找到简要介绍静态断言(static_assert)用户定义的文字实际上,当前的GCC干线已经实现了可变参数模板和静态断言。我们希望它将很快支持其他两个。我认为C ++ 1x会摇摇欲坠。
打开App,查看更多内容
随时随地看视频慕课网APP