最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

bit manipulation - JavaScript Bitwise operations - Stack Overflow

programmeradmin0浏览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 plete, it should be simple to see which key is currently depressed by asking "is this key's code in the variable?"

Thanks in advance!

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 plete, it should be simple to see which key is currently depressed by asking "is this key's code in the variable?"

Thanks in advance!

Share Improve this question asked Sep 23, 2010 at 21:39 GregGreg 21.9k17 gold badges88 silver badges109 bronze badges 6
  • 6 @Greg: You didn't have the time to read my answer for your previous question, which answered this question as well, before deleting your previous question? – Matti Virkkunen Commented Sep 23, 2010 at 21:41
  • The previous question: stackoverflow./questions/3782673/… – kennytm Commented Sep 23, 2010 at 21:56
  • @KennyTM: How did you find that? – Matti Virkkunen Commented Sep 23, 2010 at 21:57
  • @Matti: Browser history. – kennytm Commented Sep 23, 2010 at 21:58
  • @KennyTM: Ah. Here I was thinking you could find closed questions from somewhere... – Matti Virkkunen Commented Sep 23, 2010 at 22:25
 |  Show 1 more ment

4 Answers 4

Reset to default 5

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 puter: "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.

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 "bine" 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 parison 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.

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 ...

}

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./2012/02/13/using-bitflags-and-bitwise-math/

Source - https://github./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;
发布评论

评论列表(0)

  1. 暂无评论