开发者

How do I get the high- and low-order bits of a SHORT?

The function GetKeyState() returns a SHORT that contains the key's state (u开发者_运维百科p/down in the high-order bit, and toggled in the low-order). How do I get those values?


Simple bit manipulation will work. SHORTs are 16-bit integers, so to get the low- and high-order bits you can do the following:

lowBit = value & 1;
highBit = ((unsigned short) value) >> 15;

Also, note that the LOBYTE and HIBYTE macros are used to break SHORTs into low- and high-order bytes, not to test individual bits in a byte.


That's not how you use the return value of GetKeyState(). Do it like this instead:

SHORT state = GetKeyState(VK_INSERT);
bool down = state < 0;
bool toggle = (state & 1) != 0;


The normal way to check the result of GetKeyState or GetAsyncKeyState is bitwise-and with 0x8000 (binary 1000 0000 0000 0000).

#define IS_DOWN( GetKeyState(x) & 0x8000 )
if( IS_DOWN( VK_ESCAPE ) ) // escape is down.


If Google brought you here like it did me while trying to find information on GetKeyboardState() instead of GetKeyState(), note that it acts on an array of BYTE, not SHORT.

  • If you choose to bitwise AND, you should use 0x80, not 0x8000.
  • If you shift, use >> 7, not >> 15.

For example, to determine if either CTRL keys are down:

BYTE keyboardState[256];
GetKeyboardState(keyboardState);
if (keyboardState[VK_CONTROL] & 0x80)
{
    std::cout << "control key!" << std::endl;
}


#define LOBYTE(a) ((CHAR)(a))
#define HIBYTE(a) ((CHAR)(((WORD)(a) >> 8) & 0xFF))


WORD == SHORT, HIWORD works on DWORDs, HIBYTE works on SHORTs/WORDs.


GetKeyState currently returns SHORT datatype, which typedef from short. short resides within range –32,768 to 32,767. One approach to detect highest enabled bit (key is down) is make it unsigned and then to query against 0x8000 const value.

Another approach is to keep value as signed and simply compare it against 0.

bool bIsKeyDown = GetKeyState(VK_SHIFT) < 0;

Like it's mentioned in here: https://stackoverflow.com/a/5789914/2338477

all negative values have highest bit enabled, as all positive values and zero have highest bit disabled.

This is example table for char, but same is applicable to short data type as well, only table will be slightly larger.

bits  value
0000    0
0001    1
0010    2
0011    3
0100    4
0101    5
0110    6
0111    7
1000   -8
1001   -7
1010   -6
1011   -5
1100   -4
1101   -3
1110   -2
1111   -1

And key toggling can be checked using normal "and" operation, like mentioned by other answers here:

bool bIsKeyToggled = GetKeyState(VK_SHIFT) & 1;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜