如何使用按位运算符返回0或1 [英] How to use bitwise operators to return a 0 or 1

查看:1052
本文介绍了如何使用按位运算符返回0或1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的功能发生在一个32位int和我需要返回一个0或1,如果这个数字中的任何位置,甚至有一个1。我不能使用任何条件语句,我也只能在一次访问8位。

My function takes in a 32 bit int and I need to return a 0 or 1 if that number has a 1 in any even position. I cant use any conditional statements I also can only access 8 bits at a time.

下面是一个例子输入:
10001000 01011101 00000000 11001110

Here is an example input: 10001000 01011101 00000000 11001110

1),AA(10101010在一个变量移位和并把它们),并存储每个之一。

1) Shift the bits and and them with AA(10101010) and store each one in a variable.

int a = 10001000
int b = 1000
int c = 0
int d = 10001010

现在我需要返回一个0,如果有没有设置奇数位和1个是否有。我们可以看到有。所以,我需要将这些组合成一个号码,然后使用!操作符返回0或1。这是我遇到麻烦了。

Now I need to return a 0 if there were no odd bits set and 1 if there were. As we can see there were. So I need to combine these into one number and then use the !! operator to return 0 or 1. This is where I am having trouble.

int valueToReturn = a | b | c | d;

现在我需要说:

return !!valueTOReturn; 

它不返回正确值的任何人都可以给我任何见解?

It is not return the right value can anyone give me any insight???

我不能使用任何条件语句像|| &功放;&安培;

I cannot use any condition statements like || &&

我想通了。一切,我说给出了正确的答案,但我抓住了错误的价值为我的变量之一。感谢所有帮助!

I figured it out. Everything I said gives the right answer but I was grabbing the wrong value for one of my variables. Thanks for all the help!

推荐答案

首先,你不存储位你想的方式。

First of all, you're not storing bits the way you're thinking.

int a = 10001000

实际上是10001000(其在二进制b100110001001101001101000)。

is actually 10,001,000 (which in binary, b100110001001101001101000).

您说这个函数接受一个32位整数,所以你能做的就是提取每个8位部分,像这样:

You say that the function takes in a 32-bit integer, so what you can do is extract each of the 8-bit portions like so:

unsigned char a, b, c, d;
a = (unsigned char)(input & 0xff);
b = (unsigned char)((input >> 8) & 0xff);
c = (unsigned char)((input >> 16) & 0xff);
d = (unsigned char)((input >> 24) & 0xff);

现在您就可以执行屏蔽/测试操作:

Now you can perform your masking/testing operation:

return (0xAA & a) | (0xAA & b) | (0xAA & c) | (0xAA & d);

这篇关于如何使用按位运算符返回0或1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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