A simple and general way would be to use a function like this:
void *memxor(void *p, int val, size_t size) { unsigned char *pb = p; while (size-- > 0) *pb++ ^= (unsigned char)val; return p; }
And use it like this:
sample_struct s; ... memxor(&s, ~0, sizeof s);
If for some reason you want to optimize more, try the following:
void meminvert(void *ptr, size_t size) { if (((uinptr_t)ptr | size) & (sizeof(unsigned int) - 1)) { unsigned char *p = ptr, *pe = pb + size; while (p < pe) *p++ ^= ~0U; } else { unsigned int *p = ptr, *pe = p + size / sizeof *p; while (p < pe) *p++ ^= ~0U; } }
You can try and check if the optimized version really matters. This will require both a huge structure and an unreasonable number of calls. Optimization like this is rarely necessary and often erroneous.
source share