~ bit-wise unary operator

Hrvoje Niksic hniksic at xemacs.org
Thu Sep 27 00:23:59 CEST 2007


Ladislav Andel <ladaan at iptel.org> writes:

> Hello, why ~ bit-wise unary operator returns -(x+1) and not bit
> inversion of the given integer?

On 2s-complement architectures, -(x+1) *is* bit inversion of the given
integer.

> example:
> a = 7978
> a = ~a
> python returns -7979
>
> but I need to get back 57557 as in C language.

Python does exactly what C does in this case.

$ cat a.c
#include <stdio.h>
int main(void)
{
  int a = 7978;
  a = ~a;
  printf("%d\n", a);
  return 0;
}
$ gcc a.c
$ ./a.out
-7979

If you want 16-bit unsigned arithmetic, use 2**16 + ~a, which yields
57557.



More information about the Python-list mailing list