Quote:
Originally Posted by pan64
val & mask clears the bits outside of the mask (so will keep only what is masked), val & ~mask will clear the bits specified by mask and will not modify the others.
|
The responses received to my query helped me realize the clear difference (using the code example that follows---included just for the use of any other novices with a question similar to mine) that:
1) using the &= mask parsing serves to leave bits ON which are ON in the mask, and turns others OFF, while:
2) using the & ~mask parsing leaves bits unchanged (ON) which are NOT ON in the mask, and turns OFF bits which are ON in the mask.
Thanks again to all.
Code:
#include <stdio.h>
char * itobs(int, char *);
void show_bstr(const char *);
int main(void)
{
char bin_str[8 * sizeof(int) + 1];
int number, mask;
int result;
puts("Enter integers and see them in binary.");
puts("Non-numeric input terminates program.");
while (scanf("%u", &number) == 1)
{
itobs(number,bin_str);
printf("%d is ", number);
show_bstr(bin_str);
putchar('\n');
puts("Enter integers for the mask.");
scanf("%u", &mask);
itobs(mask,bin_str);
printf("%d is ", mask);
show_bstr(bin_str);
putchar('\n');
// now show results
result = number & mask;
itobs(result,bin_str);
puts("result of number &= mask is");
show_bstr(bin_str);
putchar('\n');
result = number & ~mask;
itobs(result,bin_str);
puts("result of number & ~mask is");
show_bstr(bin_str);
putchar('\n');
}
puts("Bye!");
return 0;
}
char * itobs(int n, char * ps) // remember that n is in binary format
{
int i;
static int size = 8 * sizeof(int);
for (i = size - 1; i >= 0; i--, n >>= 1)
ps[i] = (01 & n) + '0'; // sets val to either 0 + 0 or 1 + 0
ps[size] = '\0';
return ps;
}
/* show binary string in blocks of 4 */
void show_bstr(const char * str)
{
int i = 0;
while (str[i])
/* not the null character */
{
putchar(str[i]);
if (++i % 4 == 0 && str[i])
putchar(' ');
}
}