Skip to content

Instantly share code, notes, and snippets.

@jgrahamc
Last active August 29, 2015 14:21
Show Gist options
  • Save jgrahamc/3ddb36bb828a894add15 to your computer and use it in GitHub Desktop.
Save jgrahamc/3ddb36bb828a894add15 to your computer and use it in GitHub Desktop.
#include "stdint.h"
#include "stdio.h"
void main(int argc, void *argv[]) {
uint64_t i;
for (i = 0; i < 2^32; i++) {
uint32_t x = (uint32_t)i;
uint32_t l = (-x-1) & 0xffff;
uint32_t r = ~x & 0xffff;
if (l != r) {
printf("Differs for %x: (%x, %x)\n", x, l, r);
}
}
}
@sinic
Copy link

sinic commented May 14, 2015

2^32 is 2 XOR 32 (i.e., 34), not UINT32_MAX (i.e., 4294967295). Then again, your relational operator takes precedence over the bit twiddling. As to your original question: two's complement guarantees that -n - 1 equals ~n. Even K&R got away with assuming that representation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment