Bitwise XOR of two memory blocks

Hey all,

I am working on implementing a specialized keypad into my app. When a key is pressed this keypad basically reports the state of every key (up or down). This is stored in a memory block. I need to be able to know when a new key is pressed.

So for example, I press the very first key on the keypad. I handle the event and then store the memory block in the object. Now, without letting go of my first press, I press the key next to it. Now I get a memory block from the keypad that shows both keys being held down, but I only want to know the new key.

I am thinking that a BitWise XOR function on the new memory block and the stored memory block will give me what I want. Keys that aren’t pressed in each memory block will return 0. Keys that are pressed in both memory blocks will return a 0. Only a key that is pressed in the second and not in the first will return a 1. It’s perfect.

My question is, can I get the Integer value of the entire memory blocks and do the comparison there or do I need to do it on each byte? I’m thinking I may have to do this a byte at a time as so far I’m not getting what I want or expect when getting the Int value of the memory blocks and then perform the bitwise XOR operation…

Is there a better way to do it?

Depending on the size of your MemoryBlock, you can do it in chunks of UInt16, UInt32, or even UInt64. The value returned will tell you which bits are set in that chunk, and then you use the chunk starting point to determine the keys.

Have you considered (or is it even possible) returning an array of Key objects, or even a Dictionary, instead of a MemoryBlock?

It’s a USB device and the read function from Christian’s HIDAPIDeviceMBS returns a memory block. Which is fine because the data returned by the keypad is basically an array that indicates which row and column a button is pushed based on the byte and then the value of that byte.

So for example, if you press the first key in row 1, then key data comes back as 1 0 0 0 (on this key pad I have 4 columns and 6 rows). If I press key 4 in row 1 the data comes back as 0 0 0 1. If I press key 1 on row 6, I get 32 0 0 0. Key 3 in 5 is 0 0 16 0.

I know which column is pressed based on the byte. I know which row is pressed based on the value of the byte (1,2,4,8,16,32).

There’s other data in the memory block as well but these are the key pieces. An XOR on the bytes gives me exactly what I want to know…

I’m thinking it is easiest to do it a byte at a time on the pertinent bytes…

And actually doing a bitwise XOR on the entire memory blocks does give me the difference in keystrokes I am looking for. I had some sort of an error in my code previously. It does wipe out some of the other data that’s been read but for determining the new key that was pressed it does the right thing.