在没有条件语句的情况下访问第n位 [英] Access to nth bit without a conditional statement

查看:97
本文介绍了在没有条件语句的情况下访问第n位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个序列:

1010

1是MSB.

如果奇数位为0,则我的函数需要返回整数0,如果其为1,则需要返回1.

My function needs to return an integer of 0 if an odd bit is 0 or a 1 if its a 1.

我不能使用任何for循环或类似性质的东西来查看是否需要返回0或1.有人对此有任何建议吗?

I cannot use any for loops or anything of that nature to see if I need to return a 0 or 1. Does anyone have any suggestions how to go about this.

我当时正在考虑使用not操作,但是我可以弄清楚如何正确使用它.

I was thinking about using a not operation but I can figure out how to exactly use it.

到目前为止,我正在使用1010 ... 10的序列,然后将其相加.对上面的操作这样做将使我得到1010.现在,我需要确定是否返回1或0.

So far I am using a sequence of 1010...10 and then anding it. Doing that to the above would get me 1010. Now I need to find out if I return a 1 or a 0.

推荐答案

假设我们正在谈论32位整数.我假设您想知道是否将ANY ODD位设置为(1).

Say we're talking about 32bit integers. I assume you want to know if ANY ODD bit is SET (1).

为此,我们创建一个如下所示的整数:

To do this we create an integer that looks like this:

10101010101010101010101010101010

现在,如果以此与(&),则所有偶数位都将被过滤掉.现在,如果数字不为零,则设置一个或多个奇数位.在C中:

Now, if we AND (&) by this, all the even bits get filtered out. Now if the number is not zero one or more odd bits were set. In C:

#include <stdint.h>

int hasodd(uint32_t x) {
    // 0xAAAAAAAA = 10101010101010101010101010101010
    // double negation to turn x>0 into 1 and leave 0 alone
    return !!(x & 0xAAAAAAAA); 
}

如果您要返回是否设置了第N位,则此方法有效.它将1右移到正确的位置以过滤掉所有不相关的位:

If you meant that you should return whether the Nth bit is set, this works. It right-shifts a 1 to the correct position to filter out all the irrelevant bits:

#include <stdint.h>

int nthbitset(uint32_t x, int n) {
    return x & (1 << n);
}

这篇关于在没有条件语句的情况下访问第n位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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