我如何从int获得一点? [英] How am I getting a single bit from an int?

查看:98
本文介绍了我如何从int获得一点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解:

int位=(数字>> 3)& 1;

int bit = (number >> 3) & 1;

请给我左起第3位,所以说8是1000,所以应该是0001.

Will give me the bit 3 places from the left, so lets say 8 is 1000 so that would be 0001.

我不明白的是,& 1"将如何删除除最后一位以外的所有内容,从而仅显示"1"的输出.我知道这行得通,我知道如何从int中获取一点,但是代码如何提取单个位呢?

What I don't understand is how "& 1" will remove everything but the last bit to display an output of simply "1". I know that this works, I know how to get a bit from an int but how is it the code is extracting the single bit?

代码...

int number = 8;
int bit = (number >> 3) & 1;
Console.WriteLine(bit);

推荐答案

除非我从学校毕业的布尔代数使我失败,否则所发生的情况应等同于以下内容:

Unless my boolean algebra from school fails me, what's happening should be equivalent to the following:

              *
  1100110101101  // last bit is 1
& 0000000000001  // & 1
= 0000000000001  // = 1

              *
  1100110101100  // last bit is 0
& 0000000000001  // & 1
= 0000000000000  // = 0

因此,当您执行& 1时,基本上要做的是将所有其他位清零,最后一位将保留原样.或者更确切地说,您是在两个数字之间执行按位AND运算,其中其中一个恰好是1且所有前导位都设置为0

So when you do & 1, what you're basically doing is to zero out all other bits except for the last one which will remain whatever it was. Or more technically speaking you do a bitwise AND operation between two numbers, where one of them happens to be a 1 with all leading bits set to 0

这篇关于我如何从int获得一点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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