~ bit-wise unary operator

Paul Hankin paul.hankin at gmail.com
Thu Sep 27 00:25:09 CEST 2007


On Sep 26, 11:14 pm, Ladislav Andel <lad... at iptel.org> wrote:
> Hello,
> why ~ bit-wise unary operator returns -(x+1) and not 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.
>
> which is also in binary
> 0001111100101010
> and inverted
> 1110000011010101
>
> Is here any other operator or do I have to write it on my own?

The size of int is an implementation detail in C, so you may not get
57557 (in fact, you're only likely to get that answer if a is an
unsigned short on any modern architecture. But if that's what you
want, try
def invert(x):
  return ~x & 0xffff

--
Paul Hankin




More information about the Python-list mailing list