Keyboard state in bits?
Posted: Tue Oct 04, 2011 12:30 am
I thought it would be terribly wasteful to store
my keyboard state in an array of anything but bits.
So i wrote this code today, but have not tried it.
What is your opinion on this matter?
Does this code look ok, or is it junk?
my keyboard state in an array of anything but bits.
So i wrote this code today, but have not tried it.
What is your opinion on this matter?
Does this code look ok, or is it junk?
Code: Select all
/* Must be divisible by 8. */
#define MAX_KEYBOARD_BUTTONS 128
/* Safe type for keys. */
typedef enum {
...
KEY_A = 'A',
KEY_B = 'B',
...
KEY_Z = 'Z',
...
KEY_a = 'a',
KEY_b = 'b',
...
KEY_z = 'z',
...
} key_t;
/* Don't ever access this directly. */
unsigned char kb_state[MAX_KEYBOARD_BUTTONS/8];
/* Returns the up/down state of the specified key. */
bool KB_GetKeyState (key_t key)
{
return kb_state[key >> 3] & (1 << (key & 7));
}
/* Sets the up/down state of the specified key. */
void KB_SetKeyState (key_t key, bool down)
{
if (down == false)
kb_state[key >> 3] &= ~(1 << (key & 7));
else
kb_state[key >> 3] |= (1 << (key & 7));
}