想看一些关于位屏蔽的示例代码? [英] want to see some example code on bit masking?

查看:64
本文介绍了想看一些关于位屏蔽的示例代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道有点掩盖。它怎么工作?这是非常紧急的,请帮助我......

解决方案

比特屏蔽是一种使用变量位作为开/关二进制开关而不是每个开关都有一个单独的变量。


假设你需要一个开关电源(开/关)PaperLoaded(开/关)和TonerLow(开/关)。您可以使用值为1或0的三个变量。或者您可以在一个变量中使用三位,因为位值是打开/关闭的。


如果您使用的是C ++,则应使用位集<>模板。只有在C中才能进行位掩码。


假设Power为0位,PaperLoaded为1位且TonerLow为2位:


011


表示(从右到左)电源打开,PaperLoaded打开,TonerLow关闭。


这些值一起是整数3.


要测试PaperLoaded ON,您需要找到位1的值。您可以使用掩码来执行此操作:


010


面具的ON位在正确的位置,在这种情况下是位1.


接下来,你和这个面具一起使用yuor位:


010

011


,结果是010,因为AND和AND只产生1比特是1.


所以,010是你的面具,010是你的结果。当这两个相等时,位1为ON。你掩盖了这一点。


这个代码使用1< 1. 1是0000001,1左移1是

00010:

展开 | 选择 | 换行 | 行号


在上面的综合处理之后,我不愿意采取这种做法,因为我不是专家,但这里是我的书用C ++编程的编码示例。作者:John R Hubbard第331页

展开 | 选择 | Wrap | < span class =codeLinkonclick =LineNumbers(this);>行号


建议保持位变量的变量无符号

I have no idea about bit masking.How does it work?? It''s very urgent ,please help me...

解决方案

Bit masking is a way to use the bits of a variable as on/off binary switches rather than have a separate variable for each switch.

Let''s say you need a switch for Power (on/off) PaperLoaded (on/off) and TonerLow (on/off). You could three variables with values of 1 or 0. Or you could use three bits inside one variable instead since bit values are on/off.

If you are using C++ you should use the bitset<> template. Only in C should you be bitmasking.

Let''s assume Power is bit 0, PaperLoaded is bit 1 and TonerLow is bit 2:

011

represents (right to left) Power is ON,PaperLoaded is ON and TonerLow is OFF.

Together these values are an integer 3.

To test for PaperLoaded ON you need to find the value of bit 1. You use a mask to do this:

010

The mask has an ON bit in the correct position, in this case bit 1.

Next, you AND this mask with yuor bits:

010
011

and the result is 010 since and AND produces a 1 only if both bits are 1.

So, 010 is your mask and 010 is your AND result. When these two are equal, bit 1 is ON. You have masked that bit.

The code for this uses 1 < 1. A 1 is 0000001 and a 1 shifted left by 1 is
00010:

Expand|Select|Wrap|Line Numbers


I hesitate to take this further after the comprehensive treatment above as am no expert however here is a coded example from my book "Programming with C++" by John R Hubbard pp 331

Expand|Select|Wrap|Line Numbers


It is advisable for the variable holding the bit variables to be unsigned.


这篇关于想看一些关于位屏蔽的示例代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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