#include <stdio.h>
char *toBinFormat(int n);
int main(int argc, char **argv)
{
// bit level XOR (^)(exclusive or)
// result is 0 when we have two zeroes or two ones
// result is 1 when one of the bits is 1 and the other is zero
// with XOR you can toggle the bits between 1 and 0
char tmp;
tmp = 7 ^ 1;
printf("%3d = %s\n", 7, toBinFormat(7));
printf("%3d = %s\n", 1, toBinFormat(1));
printf("tmp = 7 ^ 1 = %3d = %s\n\n", tmp, toBinFormat(tmp));
tmp = 7 ^ 3;
printf("%3d = %s\n", 7, toBinFormat(7));
printf("%3d = %s\n", 3, toBinFormat(3));
printf("tmp = 7 ^ 3 = %3d = %s\n\n", tmp, toBinFormat(tmp));
tmp = 7 ^ 7;
printf("%3d = %s\n", 7, toBinFormat(7));
printf("%3d = %s\n", 7, toBinFormat(7));
printf("tmp = 7 ^ 7 = %3d = %s\n\n", tmp, toBinFormat(tmp));
tmp = 7 ^ 32;
printf("%3d = %s\n", 7, toBinFormat(7));
printf("%3d = %s\n", 32, toBinFormat(32));
printf("tmp = 7 ^ 32 = %3d = %s\n\n", tmp, toBinFormat(tmp));
tmp = 7 ^ 8;
printf("%3d = %s\n", 7, toBinFormat(7));
printf("%3d = %s\n", 8, toBinFormat(8));
printf("tmp = 7 ^ 8 = %3d = %s\n\n", tmp, toBinFormat(tmp));
return(0);
}
char *toBinFormat(int n)
{
static char binary_value[9]; // without static binary_value is a local
// array that disappear after return
int i;
for(i = 0; i < 8; i++)
{
binary_value[i] = n & 0x80 ? '1' : '0';
n <<= 1;
}
binary_value[i] = '\0';
return binary_value;
}
/*
run:
7 = 00000111
1 = 00000001
tmp = 7 ^ 1 = 6 = 00000110
7 = 00000111
3 = 00000011
tmp = 7 ^ 3 = 4 = 00000100
7 = 00000111
7 = 00000111
tmp = 7 ^ 7 = 0 = 00000000
7 = 00000111
32 = 00100000
tmp = 7 ^ 32 = 39 = 00100111
7 = 00000111
8 = 00001000
tmp = 7 ^ 8 = 15 = 00001111
*/