为什么某些情况需要使用“按位”运算符而不是“逻辑”/“等号”运算符? [英] Why do certain situations require the use of 'bitwise' operators instead of 'logical' / 'equality' operators?

查看:228
本文介绍了为什么某些情况需要使用“按位”运算符而不是“逻辑”/“等号”运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

第二天我试图使用SDL多媒体库编写一个小型的C ++编程,我碰到了这个小小的陷阱,我最终通过试错来解决。问题是,我明白我做了什么来解决问题,但我并不真正了解问题的性质!



问题是与键盘事件处理SDL。处理单键按键退出程序的代码是简单直观的。 [eventQueue是一个SDL_Event结构]

  //检查按键事件.. 
if(eventQueue.type == SDL_KEYDOWN)
{
//注意:使用布尔逻辑'=='equals operator ..
if(eventQueue.key.keysym.sym == SDLK_ESCAPE)
{
running = false;
}
}

在上面的代码中,只需按ESCAPE键它自己结束主循环并导致程序清理和关闭...



然而...需要处理使用修饰符的按键的代码键(shift / alt / ctrl)使用'=='运算符无效。我花了很多时间才发现,我需要使用一个按位AND运算符而不是等式(逻辑?)运算符。

  //检查按键事件.. 
if(eventQueue.type == SDL_KEYDOWN)
{
//注意:需要使用按位AND运算符。 。
if((eventQueue.key.keysym.mod& KMOD_ALT)&&(eventQueue.key.keysym.sym == SDLK_F4))
{
running = false;
}
}

我的困惑来自于,当使用'keysym.sym'成员,逻辑运算符'=='工作正常,但是当使用'keysym.mod'成员时,有必要使用'&'按位AND运算符。



现在,如果我不得不猜测,我会说,这与keysym.sym只需要处理一个单一的数值,键盘,而'keysym.mod'必须处理shift,ctrl和alt键的各种组合??



总结一下我的问题: 为什么会这样?有没有办法学习,除了试错,是否需要将某一数据与按位或逻辑/等式运算符进行比较?为什么keysym.sym == SDLK_F4工作正常,但keysym.mod == KMOD_ALT不是?为什么涉及十进制数的操作与比较位的操作有不同的结果?还有还有逻辑运算工作和按位运算不起作用的情况?

解决方案

按位AND有点特别。 == 检查相等,但按位运算符允许您处理数字的各个位。



想象你的事件被定义为一个键列表:

  event = ['a','shift','ctrl'] 

然后,您可以检查特定修饰符是否是事件的一部分: p>

 如果事件中有shift:
#...
pre>

按位AND类似于语句中的。您可以将事件定义为如下二进制数:

  event = 00010010 

现在,当您执行按位AND时,您可以轻松检查以查看某个修饰符是否已应用于事件,因为修饰符也表示为二进制数:

  00010001#事件(18)
& 00010000#shift key(8)
----------
00010000#你得到一个非零的答案,所以shift键是在
--- -------

00010001#event(18)
& 00001000#z键(4)
----------
00000000#你得到零,因为z键不是事件的一部分
----------

您可以使用按位OR :

  00000001#shift key(1)
| 10100000#a键(160)
----------
10100001#生成事件(161)
----------

维基百科总结按位操作很好:


按位操作对一个或多个位模式或二进制数进行操作他们各自的位的水平。它是由处理器直接支持的快速,原始动作,用于操作比较和计算的值。在简单的低成本处理器上,通常,按位运算明显快于除法,比乘法快几倍,有时明显快于加法。虽然现代处理器通常执行加法和乘法,因为它们具有较长的指令管道和其他架构设计选择,因此按位操作一样快,因为资源的使用减少,按位操作通常会降低功耗/性能。


基本上,按位运算符可以有效地处理存储在整数位中的信息。


The other day I was trying to code a small C++ programming using the SDL multimedia library, and I ran into this small snag which I eventually solved through trial and error. The issue is, I understand what I did to solve the problem, but I don't really understand the nature of the problem!

The issue was with keyboard event handling in SDL. The code to handle a single key press to exit the program is straight forward and simple. [eventQueue is an SDL_Event structure]

//checks for keypress events..
if ( eventQueue.type == SDL_KEYDOWN )
{ 
    //note: uses the boolean logical '==' equals operator..
    if ( eventQueue.key.keysym.sym == SDLK_ESCAPE )
    {
        running = false;
    }
}

In the above code, simply pressing the ESCAPE key on its own ends the main loop and causes the program to clean up and close...

However... The code needed to handle key presses that use modifier keys (shift/alt/ctrl) did not work correct with the '==' operator. It took me ages to find out that I needed to use a bitwise AND operator instead of the equality (logical?) operator.

//checks for keypress events..
if ( eventQueue.type == SDL_KEYDOWN )
{ 
    //note: requires the use of the bitwise AND operator..
    if (( eventQueue.key.keysym.mod & KMOD_ALT ) && (eventQueue.key.keysym.sym == SDLK_F4 ))
    {
        running = false;
    }
}

My confusion here comes from the fact that, when using the 'keysym.sym' member, the logical operator '==' works fine, however, when using the 'keysym.mod' member, it was necessary to use the '&' bitwise AND operator.

Now, if I had to guess, I would say that it has something to do with the fact that 'keysym.sym' only has to handle a single numerical value that represents a single key on the keyboard, while 'keysym.mod' has to deal with various combinations of shift, ctrl, and alt keys...?

To sum up my question: Why is this the case? Is there anyway to learn, other than trial and error, whether a certain piece of data will need to be compared with bitwise or logical/equality operators? Why is it that "keysym.sym == SDLK_F4" works fine, but "keysym.mod == KMOD_ALT" does not? Why would an operation involving decimal numbers have a different result than an operation that compares the bit values? Are there also situations where logical operations work and bitwise operations would not work?

解决方案

The bitwise AND is somewhat special. == checks for equality but the bitwise AND operator allows you to work with the individual bits of a number.

Imagine your event was defined as a list of keys:

event = ['a', 'shift', 'ctrl']

You can then check to see if a particular modifier is a part of the event pretty easily:

if 'shift' in event:
  # ...

The bitwise AND is sort of like an in statement. You can define your event as a binary number like this:

event = 00010010

Now, when you perform the bitwise AND, you can easily check to see if a certain modifier has been applied to the event, as modifiers are also represented as binary numbers:

  00010001  # event (18)
& 00010000  # shift key (8)
----------
  00010000  # you get a non-zero answer, so the shift key is in the event
----------

  00010001  # event (18)
& 00001000  # "z" key (4)
----------
  00000000  # you get zero because the "z" key wasn't a part of the event
----------

You can construct an event like this using the bitwise OR:

  00000001  # shift key (1)
| 10100000  # "a" key (160)
----------
  10100001  # resulting event (161)
----------

Wikipedia sums up bitwise operations pretty well:

A bitwise operation operates on one or more bit patterns or binary numerals at the level of their individual bits. It is a fast, primitive action directly supported by the processor, and is used to manipulate values for comparisons and calculations. On simple low-cost processors, typically, bitwise operations are substantially faster than division, several times faster than multiplication, and sometimes significantly faster than addition. While modern processors usually perform addition and multiplication just as fast as bitwise operations due to their longer instruction pipelines and other architectural design choices, bitwise operations do commonly use less power/performance because of the reduced use of resources.

Basically, bitwise operators allow you to work with information stored in the bits of an integer efficiently.

这篇关于为什么某些情况需要使用“按位”运算符而不是“逻辑”/“等号”运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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