Alice
Alice

Reputation: 1400

Represent -1 as a true binary pattern

In contrast to python3, the integers are limited in python2

In [1]: bin(-1)
Out[1]: '-0b1'

-1' is represented as-0b1',

How could encode '-1' as a true binary pattern like '11111111111111111......'?

Upvotes: 0

Views: 28

Answers (1)

Amadan
Amadan

Reputation: 198418

For two's complement encoding to have any meaning, the integers need to be fixed-length. Python's integers are not, therefore such an encoding is not available for them.

Numpy does use such an encoding though. Thus,

import numpy as np
bin(np.uint8(-1))
# => '0b11111111'
bin(np.uint32(-1))
# => '0b11111111111111111111111111111111'

However, for Python's own integers, 0b11111111 is always 127, not -1; 0b11111111111111111111111111111111 is always 4294967295, not -1. Because Python integers are only limited by memory, any number of ones will only ever produce a positive integer.

Another way to force Python integers into C-like structures, this time without external libraries, is struct. E.g.

bin(struct.unpack('I', struct.pack('i', -1))[0]) # 32-bit
bin(struct.unpack('B', struct.pack('b', -1))[0]) # 8-bit

You are correct that Python2 integers are limited, but they transparently expand into longs, which are not. Python3 doesn't have this division. However, I am not aware of a situation where it would change what I wrote above.

Upvotes: 2

Related Questions