#include <stdio.h>
char *toBinFormat(int n);
int main(int argc, char **argv)
{
// bit level AND (&).
// result is 0 if one bits is 1 and other bit is zero.
// result is 0 when both bits are zero.
// result is 1 when both bits are 1
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 = 1 = 00000001
7 = 00000111
3 = 00000011
tmp = 7 & 3 = 3 = 00000011
7 = 00000111
7 = 00000111
tmp = 7 & 7 = 7 = 00000111
7 = 00000111
32 = 00100000
tmp = 7 & 32 = 0 = 00000000
7 = 00000111
8 = 00001000
tmp = 7 & 8 = 0 = 00000000
*/