Reputation: 1786
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'
Upvotes: 4
Views: 46469
Reputation: 1786
Actually the inbuild sqrt function was not working for my python 2.7.2 Ubuntu 12.04. So I used user defined function for square root. thanks everyone for help.
def ceilofsqrt(N):
answerlower = 1
answerupper = N
while answerupper - answerlower > 2:
answerupper = (answerupper + answerlower)/2 + (answerupper + answerlower)%2
answerlower = N/answerupper
guess = answerlower
while True:
if guess**2 >= N:
return guess
guess += 1
Upvotes: 0
Reputation: 41950
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)
Upvotes: 3
Reputation: 107628
bin
gives you a string representation so bin( .. ) + bin( .. )
concats two string, which is not a valid result.
>>> bin(0) + bin(1)
'0b00b1'
In case you are trying to work with actual binary data (not string representations of integer representation of binary data, which is what your code does) then you should use the struct
module instead.
Upvotes: 2
Reputation: 12054
bin will return string in format:
'0b1100000011001011101000111010110011'
With first '0b'
So, for you code, you can use this (will sum x
and y
as integers):
z=int(bin(x)[2:], 2) + int(bin(y)[2:], 2)
Or, if you want exactly first to concatinate the x
and y
as strings:
z=bin(x)[2:]+bin(y)[2:]
z=int(z,2)
Upvotes: 0