Flipping a Byte

One of the first programming puzzles I solved on my own was a byte flip. That’s the process for taking a binary value and flipping it: You transpose bits 0 through 7 to bits 7 through 0. This is a puzzle that comes up frequently in programming, but one for which no single solution is preferred.

In my case, I was writing a program that printed graphics.

Back in the early days, computer users had to write their own printer drivers. The printers came with hardcopy documentation that explained how to program the thing. So you would write a driver that handled program output, which was necessary for each installed program that used the printer. This is long before programs came with their own printer drivers or a single driver was provided by the operating system.

My printer was a C-Itoh and I was borrowing from code I had written at work for an Epson MX80 printer. The problem was that each 8-bit line of graphics output from the Epson was upside down on the C-Itoh.

At first, I was amazed that I even got the thing to print graphics. Yet I was puzzled when the graphics didn’t print correctly. It took me a while to figure out what was wrong. Figure 1 illustrates the problem visually.

Figure 1. Graphics output on two different printers. The C-Itoh output is "upside down" in a bitwise manner.

Figure 1. Graphics output on two different printers. The C-Itoh output is “upside down” in a bitwise manner.

Each line of output on the right is a flipped (upside down) copy of the line on the left. To print the graphics correctly, I had to invert the byte — flip its bits top-to-bottom.

Early printers had 8 pins in their print heads. Each pin corresponded to a bit in a byte, so to output graphics you sent bytes the printer. The bits in the byte determined which pin fired in the print head, which generated graphics output on paper.

A byte flip is not the same as an exclusive or (XOR) operation or a one’s complement. And, yes, in my budding programmer efforts, I attempted both of those logical operations to see whether they would render a quick and satisfactory result. They didn’t.

No, I had to flip each byte, reversing the order of its bits to get the output to look right.

The byte flip puzzle is one you’ll encounter rarely in your programming journeys. Many solutions are possible and you’ll find a host of them on the Internet. Back in the 1980s, however, and with no formal programming training, I had to rack my brain to devise a solution.

An advantage I had was that I was working in Assembly language. So I was manipulating the data at the lowest level, which is what helped me recognize a solution. That solution is also possible to code in C, and I’ll present my byte flip code in next week’s Lesson.

Leave a Reply