Advertisement
Redxone

[C] Keyboard State bitmap

Feb 16th, 2018
205
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.16 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <math.h>
  4. #include <stdbool.h>
  5.  
  6. typedef struct
  7. {
  8.    char* keys;
  9.  
  10. } Keyboard;
  11.  
  12. Keyboard* createKeyboard(int);
  13. bool getKeyboardKey(Keyboard* , int);
  14. void setKeyboardKey(Keyboard* , int, bool);
  15.  
  16. int main()
  17. {
  18.     Keyboard* mykeys = createKeyboard(20);
  19.     setKeyboardKey(mykeys, 5, 1);
  20.     getKeyboardKey(mykeys, 5);
  21. }
  22.  
  23. Keyboard* createKeyboard(int ksize)
  24. {
  25.     ksize = ksize < 8 ? 8 : ksize;
  26.     Keyboard* kb;
  27.     kb = malloc(sizeof(Keyboard));
  28.     kb->keys = malloc(sizeof(char)*ceil(ksize/8));
  29.  
  30.     return kb;
  31. }
  32.  
  33. bool getKeyboardKey(Keyboard* kb, int key)
  34. {
  35.     char* keyptr = kb->keys;
  36.  
  37.     int keybyte = floor(key/8);
  38.     int keybit  = (key%8);
  39.  
  40.     keyptr += (keybyte-1);
  41.     char kbyte = *keyptr;
  42.     bool kbit = (kbyte >> keybit) & 0x01;
  43.  
  44.     printf("Bits: %i",kbit);
  45.     return kbit;
  46. }
  47.  
  48. void setKeyboardKey(Keyboard* kb, int key, bool onoff)
  49. {
  50.     char* keyptr = kb->keys;
  51.  
  52.     int keybyte = floor(key/8);
  53.     int keybit  = (key%8);
  54.  
  55.     if(onoff)
  56.     {
  57.         kb->keys[keybyte-1] |= (1 << keybit);
  58.     }
  59.     else
  60.     {
  61.         kb->keys[keybyte-1] &= ~(1 << keybit);
  62.     }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement