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!
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.
backspaceis8andtabis9.In binary, that would be
1000and1001. Using binary operators, you would use OR|to “combine” the values, which would result in1001.You would check if a value is set via AND
&, e.g.1001&1000to see, if the backspace key was pressed. Unfortunately, this would also evaluate totrueif only the tab key was pressed (as its value is1001).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
statusvariable and possible statuses would beOPEN = 2,LIGHT ON = 4andALARM ON = 8.Assume that it is
OPENandLIGHT ON, i.e.Here we can easily check whether the
ALARMis on, be using AND:0110 & 1000 = 0. But if we would encodeALARM ONwith6 = 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.