I have a problem with how ~
works in C in the code snippet below:
#include <stdio.h>
int main()
{
unsigned char x[256];
int i = 0;
for(i=0; i<256; i++)
x[i] = i;
unsigned char index = 1;
unsigned char y = 0;
//Case 1
y = x[~index];
printf("%u\n", y);
//Output: 0
//Case 2
y = x[(unsigned char) ~index];
printf("%u\n", y);
//Output: 254
//Case 3
y = x[index ^ 0xFF];
printf("%u\n", y);
//Output: 254
return 0;
}
The case 1 does not return the correct result while case 2 and case 3 do. It seems to me that ~index
gets interpreted as an int and not a char. This would be OK however I do not understand why unsigned char get one extended during the bit-wise not.
Compiled using: gcc version 4.8.2 (Ubuntu 4.8.2-19ubuntu1)