I investigated GetAsyncKeyState after seeing it in a code example on how to make a fictional character move on the screen through the WASD keys.
I read this on its MSDN page:
Return value
Type: SHORT
If the function succeeds, the return value specifies whether the key
was pressed since the last call to GetAsyncKeyState, and whether the
key is currently up or down.If the most significant bit is set, the
key is down, and if the least significant bit is set, the key was
pressed after the previous call to GetAsyncKeyState.
I’m having trouble understanding the structure of the return value:
It says the type is short, so through it I suppose you could represent the number zero, in binary, as 0000000000000000, or in hex as 0x0000 (since as far as I know one hex digit represents four binary digits).
The description says that the most significant bit should be set when the key is pressed. That makes me think that, if said bit was set, the number would appear like this:
1000000000000000
To make better use of it in my program, I shortened it by translating it to hex, resulting into:
0x8000
Because 8 in hex should correspond to 1000 in binary.
When I saw that said mechanism was not working in my program (doing GetAsyncKeyState(chr) == 0x8000 would always yield false, no matter if the key was pressed or not) I took one more look to the original example I saw the function employed in first. There, the return value was being compared with the number -32767, which, when quickly translated to hex using the Windows calculator, results into the value 0xFFFFFFFFFFFF8001. Now, don’t mind the last hex digit (1) because that’s the bit used to check whether the least significant bit is also active, but I don’t want that in my case.
The things that I can’t understand here are the following:
- Why, if one hex digit represents four binary digits, and the output value of the function is a short (two bytes), here the number is represented by sixteen hex digits? Aren’t those eight bytes?
- The description of the return value said that the most significant bit would be set to 1 if the key was being pressed, and that led me to believe that the number would look like
1000000000000000, not0000000000001000. What am I missing here?
This is incorrect check. Use:
to see if the most-significant bit is set.
The value
0xFFFFFFFFFFFF8001doesn’t correspond to the actual returned value from GetAsyncKeyState. Windows calculator doesn’t know the size of the value returned from GetAsyncKeyState, so it assumes you’re working with 64-bit number. You can override it in its settings.