The byteflip() Function

When I recently researched byte-flipping on the Internet, I was surprised that the solution I used back in the 1980s wasn’t listed among the top solutions available today. That’s probably because my brain thinks like an Assembly Language programmer, so I crafted a low-level solution.

The most overt solution I saw listed a table that simply looked up the flipped values. That works, but for my solution I opted to use a bit test and the << and >> operators to shift bits in a byte. Here is the function I concocted in C, which echoes my earlier Assembly Language code:

unsigned char flipbyte(unsigned char b)
{
    int x;
    unsigned char r = 0;

    for(x=0; ; x++)
    {
        if( b &  0x80 )    /* test far left bit */
            r |=  0x80;        /* set far left bit */
        if( x == 7 )           /* don't rotate after bit 7 */
            break;
        b <<= 1;         /* rotate bits */
        r >>= 1;
    }
    return(r);
}

The for loop’s exit condition is found in the middle of its associated statements. At Line 33 (in the overall code), an if test determines when x is equal to 7. If so, the loop stops as all 8 bytes have been examined.

Within the loop, unsigned char variable b‘s left-most bit is tested (Line 31). If it’s set, the left-most bit in variable r is set (Line 32). Figure 1 illustrates this process:

Figure 1. Testing a bit and setting a bit.

Figure 1. Testing a bit and setting a bit.

The next step in the loop shifts bits in each variable: b is shifted to the left one notch; r is shifted to the right. Figure 2 illustrates this process.

Figure 1. After the bytes are shifted, left and right.

Figure 1. After the bytes are shifted, left and right.

In both instances, Lines 35 and 36 in the code, a zero (unset bit) is shifted in. The net effect is that bits are transferred from variable b on the left and they end up in variable r on the right.

The loop has to bail out early because otherwise the two shift statements would alter the final results. So the final bit is set, then the function terminates and returns the flipped byte at Line 38.

Click here to view the full code. Here is the sample output:

Original - Flipped
00000011 = 11000000
00000110 = 01100000
00001100 = 00110000
00011000 = 00011000
00110000 = 00001100
01100000 = 00000110
11000000 = 00000011

In the code, I took a byte value that was interesting to look at, 0x03, and then flipped it. The main() function has a loop that keeps shifting that value left so that you can see the progression as the bytes are flipped. The code also uses the binbin() function, which is found in my Beginning Programming with C For Dummies book.

Leave a Reply