Flip That Bit – Solution

For my solution to this month’s Exercise I went binary. Several of the C language operators work at a binary level. Because the exercise was to make a binary, or bitwise, modification, I figured a binary operator would be in order.

As a review, here are the C language bitwise operators: &, |, ^, ~, !

These operators are discussed in Chapter 17 of my book, Beginning C Programming For Dummies. The two that may appeal to you as a potential for a solution are the one’s compliment (~) and NOT (!). Of those two, however, NOT is the one you want. That’s because at a binary level 0 equals !1 and 1 equals !0.

Here is my solution:

#include <stdio.h>

#define COUNT 10

int main()
{
    _Bool toggle[COUNT] = {
        1, 0, 1, 1, 0, 1, 1, 0, 1, 0
    };
    int x;

    for(x=0;x<COUNT;x++)
    {
        printf("%d -> ",toggle[x]);
        toggle[x] = !toggle[x];
        printf("%d\n",toggle[x]);
    }

    return(0);
}

The Boolean array is created at Lines 7 through 9. The for loop at Line 12 churns through the array: The printf() statement at Line 14 displays the current binary value. Line 15 flips the bit. Line 16 displays the new value.

The output:

1 -> 0
0 -> 1
1 -> 0
1 -> 0
0 -> 1
1 -> 0
1 -> 0
0 -> 1
1 -> 0
0 -> 1

Another solution, would replace Line 15 with the ternary operator:

toggle[x] = toggle[x] ? 0 : 1;

In this solution, the value of toggle[x] is evaluated. If TRUE (1), then 0 is generated, otherwise 1 is generated. The results are the same, but it’s not the most efficient solution nor is it in the Boolean or binary theme of the Exercise. That’s okay because I’m always happy when programmers find a way to sneak in the ternary operator.

And, of course, other solutions are possible. Even an if decision tree works. And you can use multiple loops as well if you prefer a different presentation style.

Leave a Reply