The tilde operator in C

Paul Manta picture Paul Manta · Aug 26, 2011 · Viewed 84.8k times · Source

I've seen the tilde operator used in the ELF hashing algorithm, and I'm curious what it does. (The code is from Eternally Confused.)

unsigned elf_hash ( void *key, int len )
{
  unsigned char *p = key;
  unsigned h = 0, g;
  int i;

  for ( i = 0; i < len; i++ ) {
    h = ( h << 4 ) + p[i];
    g = h & 0xf0000000L;

    if ( g != 0 )
      h ^= g >> 24;

    h &= ~g;
  }

  return h;
}

Answer

GWW picture GWW · Aug 26, 2011

The ~ operator is bitwise NOT, it inverts the bits in a binary number:

NOT 011100
  = 100011