Bit Manipulation Program Demo Time

To assemble all the bit field manipulation functions into one program, I present the status portion of what could be a complex computer game. The bit fields represent the current conditions of the game’s starship. The fields are adjusted as the game progresses and various things happen.

The code is rather long, so I’m including it as a link: Click here to view the code.

Here is a sample run:

Stardate 41616
	Transporter is working.
	Warp engines online.
	Shields up.
	Phasers available.
The Klingons are attacking!
	Transporter is working.
	Warp engines online.
	This shields are down!
	Phasers available.

The program uses the enum keyword to establish constants for each bit position (Line 8):

enum {
    TRANSPORTER,
    WARP,
    SHIELDS,
    PHASERS
};

This statement appears externally, allowing these constants to be used throughout the code. That way the constants are referenced instead of bit positions, which helps make the code more readable.

For example, the statement below activates the transporter function.

bit_set(TRANSPORTER,&status);

For more readability, I could rename the bit_set() function to activate():

activate(TRANSPORTER,&status);

The code is clearer, but the point of this Lesson is to demonstrate the functions I’ve introduced already, so I kept the same names.

As a review, the functions are bit_set(), bit_reset(), and bit_test().

In the program’s show_status() function (Line 34), multiple if tests display strings to confirm the current ship’s status for the user. In a real game, these items might be displayed on the screen as lights or indicators, but the purpose here is to demonstrate how bits are manipulated individually to change certain on-off items in the game.

In my own code, I generally use an int or char variable to set the state of some TRUE or FALSE item. But when multiple on-off items need to be tracked, I revert back to individual bit fields to handle the status of the TRUE/FALSE items. It’s probably a holdover from my early days as a microcomputer programmer, and from my love of Assembly language, where bit fields are most popular.

And now the big news: Bit fields are often wider than a single bit. A field 2-bits wide can hold four status values. Back in the early microcomputer days, operating systems stored dates in a single byte, which was insane but that’s how it worked. Multiple bit fields of differing widths in a byte means that you must do more binary manipulation than I’ve demonstrated so far in this series of Lessons.

In next week’s Lesson, I demonstrate how to pull multi-bit values from a byte.

Leave a Reply