Keyboard state in bits?

Programming, for all ages and all languages.
Post Reply
bitshifter
Member
Member
Posts: 50
Joined: Sun Sep 20, 2009 4:03 pm

Keyboard state in bits?

Post 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));
}
User avatar
Combuster
Member
Member
Posts: 9301
Joined: Wed Oct 18, 2006 3:45 am
Libera.chat IRC: [com]buster
Location: On the balcony, where I can actually keep 1½m distance
Contact:

Re: Keyboard state in bits?

Post 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...
"Certainly avoid yourself. He is a newbie and might not realize it. You'll hate his code deeply a few years down the road." - Sortie
[ My OS ] [ VDisk/SFS ]
Post Reply