Page 1 of 1

Keyboard state in bits?

Posted: Tue Oct 04, 2011 12:30 am
by bitshifter
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?

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));
}

Re: Keyboard state in bits?

Posted: Tue Oct 04, 2011 1:32 am
by Combuster
Actual button states have limited use in practice. You will need to map keys to actual characters and shift states for something simple like the US layout which will take about 16 times the memory of a bitfield. Then the Europeans have deadkeys, and after that there's the really fun stuff like Cangjie or worse...