Solution for Exercise 17-8

ex1708

#include <stdio.h>

char *binbin(unsigned char n);

int main()
{
    int a,x,r;

    a = 73;
    x = 170;

    printf("  %s %3d\n",
            binbin((unsigned char)a),a);
    printf("^ %s %3d\n",
            binbin((unsigned char)x),x);
    r = a ^ x;
    printf("= %s %3d\n",
            binbin((unsigned char)r),r);
    return(0);
}

char *binbin(unsigned char n)
{
    static char bin[9];
    int x;

    for(x=0;x<8;x++)
    {
        bin[x] = n & 0x80 ? '1' : '0';
        n <<= 1;
    }
    bin[x] = '\0';
    return(bin);
}

Output

  01001001  73
^ 10101010 170
= 11100011 227

Notes

* When the two bits (first two binary numbers in the output above) are different, XOR produces a 1. When the two bits are the same — either 1 and 1 or 0 and 0 — the XOR produces a 0.