Skip to content

Instantly share code, notes, and snippets.

@prehistoricpenguin
Last active December 10, 2015 02:58
Show Gist options
  • Save prehistoricpenguin/4371940 to your computer and use it in GitHub Desktop.
Save prehistoricpenguin/4371940 to your computer and use it in GitHub Desktop.
a simple bit table program use an array of 8 chars as a bit map
/*
* @Copyright chm <prehistoricpenguin@qq.com>
*
* a simple bit table program
* use an array of 8 chars as a bit map,illuminated as below:
* 7 6 5 4 3 2 1 0
* <---------------
* 0 0 0 0 0 0 0 0 | 0
* 0 0 0 0 0 0 0 0 | 1
* 0 0 0 0 0 0 0 0 | 2
* 0 0 0 0 0 0 0 0 | 3
* 0 0 0 0 0 0 0 0 | 4
* 0 0 0 0 0 0 0 0 | 5
* 0 0 0 0 0 0 0 0 | 6
* 0 0 0 0 0 0 0 0 | 7
* ^
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#define TABLEROWS 8
#define TABLECOLUMNS 8
#define getX(val) (val >> 3)
#define getY(val) (val & 0x7)
#define setBit(val,idx) (val |= (0x1 << idx))
#define getBit(val,idx) ((val >> idx) & 0x1)
unsigned char tbl[TABLEROWS];
int setValue(int);
void printTable();
void initTable();
int main()
{
int index;
initTable();
printf("Table initialized as below:\n");
printTable();
while (1)
{
printf("please input a value(0~63,EOF to exit):\n");
if (EOF == scanf("%d", &index))
break;
assert( index >= 0 && index <= 63);
if (setValue(index) == 0)
fprintf(stderr, "error:bit %d is already setted!\n", index);
else
{
printf("bit set sucessful\n");
printTable();
}
}
return EXIT_SUCCESS;
}
void initTable()
{
memset(tbl, 0, sizeof(tbl));
}
void printTable()
{
int i, j;
printf("<---------------\n");
for (i = 0; i < TABLEROWS; ++i)
{
for (j = TABLECOLUMNS - 1; j >= 0; --j)
printf("%d ", getBit(tbl[i], j));
printf("|\n");
}
printf(" ^\n");
}
int setValue(int idx)
{
int x = getX(idx),
y = getY(idx);
/*
* bit is already setted
*/
if (getBit(tbl[x], y))
return 0;
else
{
setBit(tbl[x], y);
return 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment