Scribbling

Python Int Representation & Bit Operations 본문

Computer Science/Python

Python Int Representation & Bit Operations

focalpoint 2022. 1. 13. 12:05

Each of programming language has their own way of 'Integer Representation'.

In most languages, integers are represented with 32 bits and the most significant bit (the leftmost bit) is for the sign of it. As a result, usual '32-bit int representation' has range of [-2**31+1, 2**31].

* 2**31 (INT_MAX) is 0xFFFFFFFF

* -2*31+1 (-INT_MAX) is 0x80000000 (by 2's complement)

 

However, python has somewhat different 'Integer Representation' system. Refer to the below link for detailed instructions regarding it.

https://levelup.gitconnected.com/how-python-represents-integers-using-bignum-f8f0574d0d6b

 

How Python Represents Integers using Bignum

Learn how Python represents integer numbers of any magnitude using Bignum.

levelup.gitconnected.com

Long story short:

- python can use infinite number of bits to represent an integer

- python stores bits in 'ob_digit' arrays in unsigned format and stores number of arrays in 'ob_size'.

 

For the above reasons, '0xFFFFFFEC', which normally is -20 in other languages, is 4294967276 in python.

print(int('0xFFFFFFEC', 0))

 

 

As python has somewhat different 'intger representation', we need to be extra careful when using bit-wise operations to ints.

Note: when using bit-wise operations, both input integers are all associated with 2's complement form as other programming languages. This can be somewhat confusing, considering that python does not represent negative numbers in 2's complement format.

* Bit-wise operations

<<: shift left

>>: shift right

^: XOR

&: and

|: or

~: not

 

'Computer Science > Python' 카테고리의 다른 글

Python Grammar: Things that I forget often  (0) 2022.03.14
Python String Methods  (0) 2022.01.18
<Python> 정규표현식  (0) 2021.11.09
<Python> Decorator  (0) 2021.11.09
<Python> Iterator, Generator  (0) 2021.11.09