Getting the High-Order bit

Started by
4 comments, last by Ne0 18 years ago
HI! Im trying to get they "High-Order bit" of a short but ive totally forgotten how to do it. More specificly, im using the GetKeyState function (MSDN Artical) and need to find weather the key is pressed or not. I remember something like...

short KeyState = GetKeyState(VK_F1);
if (HIGH(KeyState) == 1)
{
    // Whateva
}
... but i really have no idea. All I need is to know if the high order bit is 1 Any help would be much appreciated :-) Tj.
Advertisement
short KeyState = GetKeyState(VK_F1);if (KeyState < 0) { // F1 pressed }




if (KeyState & 0x8000){    // key is pressed}

Assuming a short is 16 bits on any platform you'll compile for:
short KeyState = GetKeyState(VK_F1);if ((KeyState >> 15) == 1){    // Whateva}
More flexibly, assuming a byte is 8 bits:
short KeyState = GetKeyState(VK_F1);if (((KeyState >> (sizeof(short) * 8 - 1) == 1){    // Whateva}
There are plenty of other ways to do it as well. I would personally do:
short KeyState = GetKeyState(VK_F1);if ((KeyState & 0x8000) != 0){    // Whateva}
Basically, use either bit-shifts or bit-masks, or a combination of both. (About.com : Bitwise Operators)

[edit]Ghaarrr! I type a lot.[/edit]
"We should have a great fewer disputes in the world if words were taken for what they are, the signs of our ideas only, and not for things themselves." - John Locke
The portable way:
#include <climits> // or <limits.h> in Cif(keyState & (1 << (sizeof(short) * CHAR_BIT - 1))){  ...}
Woah! Thats alot of info! Thanks Antheus, Dave Hunt, Agony and Sharlin!

I ended up using the simple one (KeyState < 0)...hehe... but thanks everyone else!!

This topic is closed to new replies.

Advertisement