-1
if (GetAsyncKeyState(key) & 0x8000)

What is the meaning of "&" in the if statement above? Why we need to use it?

2

2 Answers 2

6
GetAsyncKeyState(key)

will return you 16-bit value.

Such 1010010101110110

The highest order bit contains the key state.

1010010101110110 highest order bit in bold.

Since we are only interested in the value on the highest order and mask the rest, we do the following operation & bitwise and operation.

0x8000 is hexadecimal represendtation of 1000000000000000.

key & 0x8000

==>

1010010101110110 GetAsyncKeyState(key)

&

1000000000000000 0x8000

Result:

1000000000000000 A value evaluated as true

As the example shows, we mask the bits other than the highest order bit which is set if the key is pressed otherwise zero. If block will be executed if the key is pressed.

2
  • 1
    Thanks for explaining this @Cahit. I discovered that the synchronous API doesn't work as expected when using a WindowProc callback so this was very useful. One minor comment, your binary examples are all 17 bits. Was that intentional? Jun 3, 2022 at 20:37
  • It was a mistake, not intentional. I should correct that. Thanks @JamieGarroch-MVP. Jun 3, 2022 at 22:26
1

Checking alt key is down or not.

And it is bitwise and operator.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.