如何确定一个数字中的所有设置位是否也都设置在另一个数字中? [英] How to determine if all set bits in one number is also set in another number?

查看:37
本文介绍了如何确定一个数字中的所有设置位是否也都设置在另一个数字中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出2个长度相同的二进制字符串 a b (例如 111000 110000 ),是否可以使用按位操作检查 b 中的所有设置位是否也在 a 中设置?在上面的示例中, b = 110000 在位置1和2(从左到右)中有两个设置位,这些位也都在 a = 111000 中设置./p>

我可以按字符比较两个字符串,但这太慢了.我知道我可以使用 Integer.parseInt(a,2); 之类的东西将字符串转换为数字,但是我不知道用于完成任务的按位运算.

解决方案

屏蔽位,然后检查它们是否仍然全部设置.

  int a = 0b111000;int b = 0b110000;如果((a& b)== b){...} 

Given 2 binary strings a and b of the same length (e.g. 111000 and 110000), is it possible to check if all set bits in b is also set in a using bitwise operations? In the above example, b = 110000 has two set bits in position 1 and 2 (from left to right), and those bits are also set in a = 111000.

I can compare two strings character-wise but that would be too slow. I know I can turn the strings into number with something like Integer.parseInt(a, 2); but I don't know the bitwise operations to use to achieve the task.

解决方案

Mask the bits and then check if they're still all set.

int a = 0b111000;
int b = 0b110000;

if ((a & b) == b) {
    ...
}

这篇关于如何确定一个数字中的所有设置位是否也都设置在另一个数字中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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