Introduce pet-projects dir
[lcapit-junk-code.git] / jos / bitmap.c
blobaab31740fb9b77729b8c79bd1b91a81dc51f2942
1 /*
2 * bitmap: An example of bitmap handling
3 */
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <readline/readline.h>
8 #include <readline/history.h>
10 #define LINES 3
11 #define COLS (sizeof(unsigned char) * 8)
13 static unsigned char bitmap[LINES];
15 /* bitmap_bit_is_set(): Check if bit 'num' is set.
16 * Return 0 if bit is set, 0 otherwise */
17 static int bitmap_bit_is_set(int num)
19 return (bitmap[num / COLS] & (1 << (num % COLS)));
22 /* bitmap_set_bit(): Set bit 'num' */
23 static void bitmap_set_bit(int num)
25 bitmap[num / COLS] |= 1 << (num % COLS);
28 /* bitmap_unset_bit(): Unset bit 'num' */
29 static void bitmap_unset_bit(int num)
31 bitmap[num / COLS] &= ~(1 << (num % COLS));
34 /* bitmap_print(): Print bitmap on stdout
36 * Note that the map is printed on the reverse order.
37 * For example, each word in the map is stored in
38 * memory this way:
40 * 7 6 5 4 3 2 1 0
42 * 0 0 0 0 0 0 0 0
44 * Where bit number 0 is the LSB one and bit number 7
45 * is the MSB one.
47 * But, when printing, we start to print from bit number
48 * 0 (the LSB) which gives the following screen for all
49 * the bits:
51 * 0 1 2 3 4 5 6 7
53 * 0 0 0 0 0 0 0 0
54 * 0 0 0 0 0 0 0 0
55 * 0 0 0 0 0 0 0 0
57 * See? We start printing from bit 0 to bit 7.
59 static void bitmap_print(void)
61 unsigned int count, j, i;
63 for (i = 0; i < COLS; i++)
64 printf("%d ", i);
65 printf("\n\n");
67 count = j = 0;
68 for (i = 0; i < (LINES * COLS); i++) {
69 printf("%d ", bitmap_bit_is_set(i) ? 1 : 0);
70 if (++count == COLS) {
71 printf("[%#x]\n", bitmap[j++]);
72 count = 0;
77 static void help(void)
79 printf(
80 "clear clear bitmap\n"
81 "exit exit from program\n"
82 "help this text\n"
83 "print print bitmap\n"
84 "set <hex value> set bit correspondent to value\n"
85 "unseset <hex value> unsetset bit correspondent to value\n"
89 int main(void)
91 char *cmd;
93 for (;;) {
94 cmd = readline(">>> ");
95 if (!cmd) {
96 printf("\n");
97 break;
100 if (!memcmp(cmd, "clear", 5)) {
101 memset(bitmap, 0, LINES * COLS);
102 } else if (!memcmp(cmd, "exit", 4)) {
103 free(cmd);
104 break;
105 } else if (!memcmp(cmd, "help", 4)) {
106 help();
107 } else if (!memcmp(cmd, "print", 5)) {
108 bitmap_print();
109 } else if (!memcmp(cmd, "set", 3) ||
110 (!memcmp(cmd, "unset", 5))) {
111 unsigned int num;
112 char *p = strchr(cmd, ' ');
113 if (!p) {
114 printf("Invalid use of set or unset\n");
115 } else {
116 num = strtol(p, (char **) NULL, 16);
117 if (cmd[0] == 's')
118 bitmap_set_bit(num);
119 else
120 bitmap_unset_bit(num);
122 } else {
123 printf("Invalid command: %s\n", cmd);
126 free(cmd);
129 return 0;