Originally Posted by
Jodes
Thank you. It's definitely 8. Apparently the reason is due to "Integral Promotion", a standard feature of ANSI C. Basically, ~c gets converted to an int. (Which with the XC 8 compiler is 2 bytes, and on my setup in windows is 4 bytes). I dread to think how many errors like this I'm facing in my code. And this is probably one of the easier bugs to detect if I create automated tests for all my functions!
Hmm ok, good point.
Code:
#include <stdio.h>
#include <limits.h>
int main(void)
{
unsigned char v = 0xAA;
printf("bits: %d\n", CHAR_BIT);
printf("v = %x\n", v);
printf("~v = %x\n", ~v);
if (~v == 0x55)
printf("ok 1\n");
if (v == ~0x55)
printf("ok 2\n");
if ((unsigned char)~v == 0x55)
printf("ok 3\n");
v = ~v;
if (v == 0x55)
printf("ok 4\n");
return 0;
}
Code:
bits: 8
v = aa
~v = ffffff55
ok 3
ok 4
Err, ok...
Code:
#include <stdio.h>
#include <limits.h>
#define CHARMASK ((1 << CHAR_BIT) - 1)
int main(void)
{
unsigned char v = 0xAA;
printf("bits: %d\n", CHAR_BIT);
printf("v = %x\n", v);
printf("~v = %x\n", ~v);
if (~v == 0x55)
printf("ok 1\n");
if (v == ~0x55)
printf("ok 2\n");
if ((unsigned char)~v == 0x55)
printf("ok 3\n");
printf("Mask is %x\n", CHARMASK);
if ((~v & CHARMASK) == 0x55)
printf("Mask ok\n");
else
printf("hmm: %x\n", ~v & CHARMASK);
v = ~v;
if (v == 0x55)
printf("ok 4\n");
return 0;
}
Code:
bits: 8
v = aa
~v = ffffff55
ok 3
Mask is ff
Mask ok
ok 4
I think I'll look at this a bit (hahahah, a "bit"... get it?) tomorrow.