Use Bit Flags

I have seen many programmers use dozens of chart-sized variables or Booleans to store simple on or off flags. This is a tremendous waste of space, as you only need a single bit to represent the true or false value of a flag. Instead, I like to use a lot of bit flags. Here is a hypothetical example:

We have a sprite structure for our game. This structure needs to keep track of whether the sprite is invisible and if the sprite can be collided against. If you were to have one member per flag, your structure might look like this:

typdef struct sprite_s
{
.
.
.
char nHidden
char nCollide
.
.
.

} sprite_t;
Sure, you are pretty crafty using bytes instead of whole integers to store this flag. But if you use bit flags, you can reduce this by half:

#define BITFLAG_HIDDEN 0x01
#define BITFLAG_COLLIDE 0x02

typdef struct sprite_s
{
.
.
.
unsigned char nFlags
.
.
.
} sprite_t;
Now we only need a single character, nFlags, to hold both flags. A byte is 8 bits. We use two of these to represent the hidden and collision states. For instance, if we want to set the hidden bit, simply OR in the bit flag defined up top:

nFlags |= BITFLAG_HIDDEN;

Now, the first bit is turned on. If we want to turn this bit on, we AND the flags with the inverse of the bit flag that we wish to remove:

nFlags &= ~BITFLAG_HIDDEN;
The first bit is now cleared. The great thing is that we can combine the flags like this:

nFlags |= (BITFLAG_HIDDEN | BITFLAG_COLLISION);
To determine if a bit flag is turned on, use the bitwise AND operation:

if (nFlags & BITFLAG_HIDDEN)
return;
In this case, bail out of the function if the sprite is not visible. This code fragment would be something that you may see in a sprite drawing loop.

Of course, we have only defined two bit flags. A byte can hold 8. If you need more, you can use a short for 16 bits or an integer for 32 bits. Make sure you define the flags field as unsigned. Otherwise, you will have issues reading the values in the debugger when you turn on the sign bit.

빙어, 혹은 공어?

설에 제천에 내려간 김에 의림지에 들어서 빙어튀김을 맛보고 왔습니다. (그쪽에서는 공어라고 부르던데;)

겨울에는 얼음을 깨고 낚시하는 재미에 많이들 먹지만 일반적인 생각과는 다르게 빙어는 5월에 먹는게 가장 맛있다고 하더라구요. 기름기가 전혀 없는 단백한 생선이라 그냥 잡은 즉시 먹는게 제일 좋다는 데 비위가 약해서 그렇게는 못먹어 봤고 튀겨서 먹었습니다. 단백하게 맛있긴 했지만, 비싼 가격에 비해서 왠지 멸치 먹는 느낌이 나서 별로더라구요. (사진에 보이는게 딱 만원 어치입니다)

언제 기회가 되면 이렇게 먹는 것 뿐 아니라 낚시도 해보고 싶은데 낚시는 의림지에서는 불가능하고 춘천까지 올라가야 된다더군요.