Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Python infer the number of bits to use in a binary NOT?

I'm translating this from C to Python:

int_fast16_t x;
int_fast16_t y = compute_value();
x = ~y;
y = x+1;

I don't think

y = compute_value()
y = (~y) + 1

will work: how would it know on how many bits should the binary NOT be done? (8? 16? 32?).

In the case of C, it is explicit with the type int_fast16_t, but with Python we don't know a number of bits in advance.

How do you do this in Python?

I have read How do I do a bitwise Not operation in Python? but here it's more specific: how does Python infer the number of bits to use in a binary NOT?

Example:

How does Python know if the binary NOT of 3 (0b11) should be done on 4 bits: 0b00 or on 8 bits: 0b11111100 or on 16 bits: 0b1111111111111100?

like image 770
Basj Avatar asked Dec 06 '25 16:12

Basj


2 Answers

Python int has an infinite number of bits. The only way to invert them all is to negate the sign of the number. So for example ~1 is -2. To get a specific number of bits in the result, you have to mask off those bits. (~1)&0xffff is 0xfffe which is one bit off, I assume due to two's complement.

like image 180
Mark Ransom Avatar answered Dec 08 '25 06:12

Mark Ransom


how does Python infer the number of bits to use in a binary NOT?

It uses all bits in the binary representation it has for the operand. Python integers consist of one or more longs (see Python integer objects).

How does Python know if the binary NOT of 3 (0b11) should be done on 4 bits: 0b00 or on 8 bits: 0b11111100 or on 16 bits: 0b1111111111111100?

There is no case where it would be just 4 or 8 bits. It is done on all bits in the 64 bits it has for the integer (or a multiple of that, if the original value needed more long words).

like image 41
trincot Avatar answered Dec 08 '25 08:12

trincot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!