~ bit-wise unary operator

L

Ladislav Andel

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?

Thank you,
Lada
 
H

Hrvoje Niksic

Ladislav Andel said:
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.
 
P

Paul Hankin

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
 
G

Grant Edwards

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.

It's not what C language returns, but if you want 57557, you
can get it like this:
57557
 
M

Michal Bozon

cau,
maybe int is represented internally as a signed integer

you can use numpy types:
57557

-m.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,954
Messages
2,570,116
Members
46,704
Latest member
BernadineF

Latest Threads

Top