如果发现每个偶数位使用位运算符设置为0 [英] Find if every even bit is set to 0 using bitwise operators

查看:330
本文介绍了如果发现每个偶数位使用位运算符设置为0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个32位的int我只能在同一时间访问8位。我需要找出如果每个连位设置为0,如果它的真实,否则为1。

I have a 32 bit int I can only access it 8 bits at a time. I need to find out if every even bit is set to 0 and return 0 if its true and 1 otherwise.

到目前为止,我将用我的转变INT分成4个,8位变量。
诠释A,B,C,D

So far I am going to split my int using shifts into 4, 8 bit variables. int a, b, c, d

现在我要他们不要因此现在如果该位被设置为1,而不是0我将测试。
为了测试如果将其设置为1将我和他们通过01010101.

Now I am going to not them so now I will test if the bit is set to 1 instead of 0. To test if its set to 1 I will and them by 01010101.

现在我不知道如何分辨每一个偶数位被设置为1,如果/为/ while循环或任何条件语句,需要使用位运算符我不能使用。有任何想法吗????

Now I dont know how to tell if every even bit is set to 1. I cannot use if/for/while loops or any conditional statements and need to use bitwise operators. Any ideas????

推荐答案

好了,你已经创建了一个位掩码。 (01010101)

OK, so you've created a bit mask. (01010101)

 if ((value & bit_mask) == bit_mask)

那么你知道,那是在 bit_mask 设置每个位也设置值



更新:(读问题后正常)

您要检查每一秒位设置为0(未设置为1,因为我的上述检查不正确的答案)

You want to check if every second bit is set to 0. (Not set to 1, as my incorrect answer above checks for)

有两个同样有效的方法:
我们做位掩码相反(10101010)

There are two equally valid approaches: We make the bit mask the opposite (10101010)

然后使用或操作符:

if ((value | bit_mask) == bit_mask)

这将检查那是在零每一位在 bit_mask 零值

This checks that each bit that was zero in the bit_mask is zero in value.

第二种方法是使位掩码相同(01010101),并使用AND运算符:

The second approach is to make the bit mask the same (01010101) and use the AND operator:

if ((value & bit_mask) == 0)

这会检查每个位是一个在 bit_mask

This checks that each bit that is one in the bit_mask is zero in value.

这篇关于如果发现每个偶数位使用位运算符设置为0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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