Basj
Basj

Reputation: 46563

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?

Upvotes: 3

Views: 134

Answers (2)

trincot
trincot

Reputation: 350725

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).

Upvotes: 1

Mark Ransom
Mark Ransom

Reputation: 308392

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.

Upvotes: 3

Related Questions