Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python-ValueError: invalid literal for int() with base 2

I am getting error in following lines. error is not recurring but only sometimes

x,y are huge numbers of 2048 bits
z=bin(x)+bin(y)
z=int(z,2)

ValueError: invalid literal for int() with base 2: '10010101101001011011000000001111001110111110000100101000000011111111100000111010111011101111110010001101101001101000100000001100010011000010100000110100100001010110011111101101000101101001011001100110'
like image 545
Pratibha Avatar asked Sep 05 '25 03:09

Pratibha


1 Answers

Are you sure you haven't faked that error message?

The code...

>>> int('10010101101001011011000000001111001110111110000100101000000011111111100000111010111011101111110010001101101001101000100000001100010011000010100000110100100001010110011111101101000101101001011001100110', 2)
939350809951131205472627037306557272273273866819979105965670L

...works for me.

And, a concrete example of your code...

>>> x = 82349832
>>> y = 23432984
>>> z = bin(x) + bin(y)
>>> int(z, 2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 2: '0b1001110100010001111000010000b1011001011000111100011000'

...shows the problem (i.e. the 0b prefixes) in the error message.

The solution would be to either strip the prefixes with...

z = bin(x)[2:] + bin(y)[2:]
z = int(z, 2)

...or, as Martijn Pieters suggests, generate the binary representation without prefixes using format()...

z = format(x, 'b') + format(y, 'b')
z = int(z, 2)

...or, as gnibbler suggests, use the string object's format() method to do it in one call...

z = '{:b}{:b}'.format(x, y)
z = int(z, 2)
like image 179
Aya Avatar answered Sep 07 '25 21:09

Aya