Do you use bit fields?
Alan Rooks
ajrooks at watrose.UUCP
Fri Sep 28 04:37:06 AEST 1984
I have used bitfields in many applications using sets of binary flags. However,
I came across one type of problem in which their use is inconvenient. The
program was a maze generator, and i needed 4 bits for each cell, with bit i
stating whether there was a wall in direction i (i = up, down, left, right).
The problem came up when I had an int (or enum) variable, call it j,
specifying the direction number, and i wanted to check for the wall:
#define UP 0
#define DOWN 1
#define LEFT 2
#define RIGHT 3
switch(j) {
case UP:
iswall = maze[x][y].up;
break;
case DOWN:
iswall = maze[x][y].down;
break;
case LEFT:
iswall = maze[x][y].left;
break;
case RIGHT:
iswall = maze[x][y].right;
break;
}
... when i could do it this way if maze[x][y] was just an int:
iswall = (maze[x][y] & (1 << j)) != 0;
... or even simpler,
#define UP 1
#define DOWN 2
#define LEFT 4
#define RIGHT 8
iswall = (maze[x][y] & j) != 0;
... which is nice and simple. The problem exists because i want to be
able to index my bits, and C bitfields don't give you a way to do that.
Like I said however, i have found them very useful in other applications.
Alan Rooks at the University of Waterloo; ...!utzoo!watmath!watrose!ajrooks
More information about the Comp.lang.c
mailing list