二进制文字? [英] Binary literals?

查看:177
本文介绍了二进制文字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  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 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 ++编译器不会编译,但必须有一个解决方法?

解决方案

我会使用位移位运算符:

  const int has_nukes = 1<< 0; 
const int has_bio_weapons = 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的洪水更好。


In code, I sometimes see people specify constants in hex format like this:

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!!"
}

But it doesn't make sense to me to use the hex format here. Is there a way to do it directly in binary? Something like this:

const int has_nukes        = 0b00000000000000000000000000000001;
const int has_bio_weapons  = 0b00000000000000000000000000000010;
const int has_chem_weapons = 0b00000000000000000000000000000100;
// ...

I know the C/C++ compilers won't compile this, but there must be a workaround? Is it possible in other languages like Java?

解决方案

I'd use a bit shift operator:

const int has_nukes        = 1<<0;
const int has_bio_weapons  = 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;

It is even better than flood of 0's.

这篇关于二进制文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆