JavaScript 按位运算

发布于 2024-09-24 13:21:20 字数 153 浏览 4 评论 0原文

我想通过在按下按键和释放按键时使用按位运算将所有当前按下的键码存储在单个变量中。

我不确定如何正确使用按位运算,但我知道这对于这样做的人来说会非常简单。

完成后,通过询问“这个键的代码在变量中吗?”应该很容易看出当前按下的是哪个键。

提前致谢!

I would like to store all currently-pressed keycodes in a single variable by using bitwise operations when the key is pressed and when the key is released.

I'm not sure how to properly use bitwise operations, but I know this will be very simple to someone who does.

Once complete, it should be simple to see which key is currently depressed by asking "is this key's code in the variable?"

Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

得不到的就毁灭 2024-10-01 13:21:20

从技术上讲,这在单个变量中是不可能做到的,JavaScript 中没有数据类型可以存储保存位掩码(支持按位运算)所需的 256 位,您将需要使用数组来代替。

另外,除非你有文本转语音软件,你已经将其宏化为神奇地为你执行js函数,否则询问你的计算机:“这个键的代码在变量中吗?”不会做深蹲。

这样做的方法是初始化一个具有 256 个索引的数组,然后当按下某个键时,您找到相关索引并将其设置为 true ,当释放一个键时,您设置将其设置为 false

这是唯一的方法。其实没有其他的了。

This is technically impossible to do in a single variable, no datatype in javascript can store the 256 bits required to hold the bitmask (which supports bitwise operations), you will need to use an array instead.

Also, unless you have text to speech software which you've macroed to magically execute js functions for you, asking your computer: "is this key's code in the variable?" won't do squat.

The way you would do it would be to initialize an array with 256 indexes, and then when a key is pressed, you find the relevant index and set it to true and when a key is released, you set it to false

It's the only way to do it. There actually isn't any other.

弃爱 2024-10-01 13:21:20

我认为按照您想要的方式这是不可能的。 看看可用的键码。您可以看到,例如 backspace8tab9

在二进制中,这将是 10001001。使用二元运算符,您可以使用 OR | 来“组合”这些值,这将得到 1001

您可以通过 AND & 检查是否设置了值,例如 1001 & 1000 查看是否按下了退格键。不幸的是,如果仅按下 Tab 键(因为其值为 1001),则该值也会计算为 true

也就是说,如果您要测试的不同值只是 2 的幂,即 1、2、4、8、16、32 等,则只能使用此类按位比较技术,如下所示这表示二进制 1101001000...

例如,如果我们可以有一个status 变量和可能的状态为 OPEN = 2LIGHT ON = 4ALARM ON = 8。< br>
假设它是OPENLIGHT ON,即

  0010
| 0100
------- 
  0110

这里我们可以轻松检查ALARM是否打开,使用AND:0110 & 1000 = 0。但如果我们用 6 = 0110 编码 ALARM ON,我们就无法检查这一点。


您可以做的是将键码映射到 2 的某个幂值并在那里应用二进制运算。 关于位掩码的维基百科文章可能值得一读。

我希望我的解释不知何故很清楚。

I don't think that it is possible the way you want to do it. Have a look at the available keycodes. There you see, that e.g. backspace is 8 and tab is 9.

In binary, that would be 1000 and 1001. Using binary operators, you would use OR | to "combine" the values, which would result in 1001.

You would check if a value is set via AND &, e.g. 1001 & 1000 to see, if the backspace key was pressed. Unfortunately, this would also evaluate to true if only the tab key was pressed (as its value is 1001).

That said, you can only use such bitwise comparison techniques, if the different values you want to test are powers of 2 only, i.e. 1, 2, 4, 8, 16, 32 and so on, as this represents in binary 1, 10, 100, 1000,...

For example if we can have a status variable and possible statuses would be OPEN = 2, LIGHT ON = 4 and ALARM ON = 8.
Assume that it is OPEN and LIGHT ON, i.e.

  0010
| 0100
------- 
  0110

Here we can easily check whether the ALARM is on, be using AND: 0110 & 1000 = 0. But if we would encode ALARM ON with 6 = 0110, we could not check this.


What you could do is, to map the key codes to a some power of 2 value and apply binary operations there. The Wikipedia article about bitmasks might be worth reading.

I hope my explanation was somehow clear.

脱离于你 2024-10-01 13:21:20

javascript 位操作对于前 31 位通常是可靠的,从那里开始事情就开始走下坡路。因此,您可以为 31 个不同的键赋予值来充当标志。例如,如果您想跟踪四个箭头以及 A 和 B,您可以这样做。

var KEYS = { 
    LEFT:  1 << 0,
    UP:    1 << 1,
    RIGHT: 1 << 2,
    DOWN:  1 << 3,
    A:     1 << 4,
    B:     1 << 5
}

var flags = 0;

myElement.addEventListener ('keydown', function (e) { 

    switch (e.keyCode) {

        case 37: // left
        flags = flags | KEYS.LEFT;
        break;
        case 38: // up
        flags = flags | KEYS.UP;
        break;

        ... etc ...

    }

}

} , false);

function checkKeys () {

    if ( (flags & KEYS.LEFT) === KEYS.LEFT)
        alert('LEFT key pressed');
    }

    if ( (flags & KEYS.UP) === KEYS.UP )
        alert('UP key pressed');
    }

    ... etc ...

}

javascript bit operations are generally reliable for the first 31 bits, and things go downhill from there. So, you can 31 different keys which you have given a value to act as a flag. for instance, if you wanted to track the four arrows and A and B, you would do something like this.

var KEYS = { 
    LEFT:  1 << 0,
    UP:    1 << 1,
    RIGHT: 1 << 2,
    DOWN:  1 << 3,
    A:     1 << 4,
    B:     1 << 5
}

var flags = 0;

myElement.addEventListener ('keydown', function (e) { 

    switch (e.keyCode) {

        case 37: // left
        flags = flags | KEYS.LEFT;
        break;
        case 38: // up
        flags = flags | KEYS.UP;
        break;

        ... etc ...

    }

}

} , false);

function checkKeys () {

    if ( (flags & KEYS.LEFT) === KEYS.LEFT)
        alert('LEFT key pressed');
    }

    if ( (flags & KEYS.UP) === KEYS.UP )
        alert('UP key pressed');
    }

    ... etc ...

}
前事休说 2024-10-01 13:21:20

我不确定 JavaScript 中是否存在 ByteArray 这样的东西,但如果有的话,您可以像这个人在 ActionScript3 中执行他的逻辑一样执行此操作。虽然我是位标志和位标志的忠实粉丝。按位运算,我不明白他正在做的位移,而且他的大部分代码都超出了我的理解范围。我只知道它适用于我参与过的 as3 项目。

另外,如果您想了解有关位标志和位标志的更多信息,请参阅按位运算(除了位移位)查看这篇文章 - http://jwopitz.wordpress.com/2012/02/13/using-bitflags-and-bitwise-math/

来源 - https://github.com/richardlord/Asteroids/blob/master/src/no-dependency/net/ richardlord/input/KeyPoll.as

     //init the bytearray
     _states = new ByteArray();
     _states.writeUnsignedInt( 0 );
     _states.writeUnsignedInt( 0 );
     _states.writeUnsignedInt( 0 );
     _states.writeUnsignedInt( 0 );
     _states.writeUnsignedInt( 0 );
     _states.writeUnsignedInt( 0 );
     _states.writeUnsignedInt( 0 );
     _states.writeUnsignedInt( 0 );

    //on a keydown listener (note the bitwise OR for adding
    _states[ event.keyCode >>> 3 ] |= 1 << ( event.keyCode & 7 );

    //on a keyup listener (note the bitwise AND plus bitwise NOT
    states[ ev.keyCode >>> 3 ] &= ~(1 << (ev.keyCode & 7));

    //check for keydown
    return ( states[ keyCode >>> 3 ] & (1 << (keyCode & 7)) ) != 0;

    //check for keyup
    return ( states[ keyCode >>> 3 ] & (1 << (keyCode & 7)) ) == 0;

I'm not sure if there is such a thing as a ByteArray in JavaScript but if so, you could do it much like how this fellow did his logic in ActionScript3. While I am a big fan of bitflags & bitwise operations, I don't get the bitshifting he's doing and much of his code is way over my head. I just know it works on as3 projects I've worked on.

Also if you'd like to learn more about bitflags & bitwise operations (aside from the bitshifting) check out this article - http://jwopitz.wordpress.com/2012/02/13/using-bitflags-and-bitwise-math/

Source - https://github.com/richardlord/Asteroids/blob/master/src/no-dependencies/net/richardlord/input/KeyPoll.as

     //init the bytearray
     _states = new ByteArray();
     _states.writeUnsignedInt( 0 );
     _states.writeUnsignedInt( 0 );
     _states.writeUnsignedInt( 0 );
     _states.writeUnsignedInt( 0 );
     _states.writeUnsignedInt( 0 );
     _states.writeUnsignedInt( 0 );
     _states.writeUnsignedInt( 0 );
     _states.writeUnsignedInt( 0 );

    //on a keydown listener (note the bitwise OR for adding
    _states[ event.keyCode >>> 3 ] |= 1 << ( event.keyCode & 7 );

    //on a keyup listener (note the bitwise AND plus bitwise NOT
    states[ ev.keyCode >>> 3 ] &= ~(1 << (ev.keyCode & 7));

    //check for keydown
    return ( states[ keyCode >>> 3 ] & (1 << (keyCode & 7)) ) != 0;

    //check for keyup
    return ( states[ keyCode >>> 3 ] & (1 << (keyCode & 7)) ) == 0;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文