Chad wrote:
For some strange reason, I thought the following would give me a value
of 168, not 166. My reasoning was that 678 - 255 - 255 = 168.
Why you think 'a & b' should mean 'a - b - b' is a mystery.
#include <stdio.h>
int main(void) {
unsigned long a = 678;
unsigned long ff = 255;
unsigned long c = a & ff;
printf("The value is: %u \n", c);
^^^
%u is the specifier for an unsigned int, not an unsigned long (%lu)
return 0;
}
The value is: 166
$
What am I missing here?
Any understanding of logical operators? See the version below, with a
note following.
#include <stdio.h>
int main(void)
{
unsigned a = 678;
unsigned ff = 255;
unsigned c = a & ff;
char format[] = "value of %6s is %#011o (octal), %010u (decimal)\n";
printf(format, "a", a, a);
printf(format, "ff", ff, ff);
printf(format, "a & ff", a & ff, a & ff);
printf(format, "c", c, c);
return 0;
}
value of a is 00000001246 (octal), 0000000678 (decimal)
value of ff is 00000000377 (octal), 0000000255 (decimal)
value of a & ff is 00000000246 (octal), 0000000166 (decimal)
value of c is 00000000246 (octal), 0000000166 (decimal)
[note]
considering the rightmost 4 octal digits
01 & 00 is binary 001 & 000, obviously 000 (0 octal)
02 & 03 is binary 010 & 011, obviously 010 (2 octal)
04 & 07 is binary 100 & 111, obviously 100 (4 octal)
06 & 07 is binary 110 & 111, obviously 110 (6 octal)
so 01245 & 0377 is 0246 or 166 decimal.