Mar-17-2020, 02:48 AM
(Mar-17-2020, 02:18 AM)medatib531 Wrote: This represents a large number which is even. I want to convert this to an odd number as efficiently as possible.This needs to be clarified.
Let we have a bytestring, e.g.
x = b'\x12\xfe'
. This bytesting represents an even integer,>>> int.from_bytes(x, byteorder='big')
Output:4862
Now, you want to turn this integer out to some odd integer. Ok, the fastest way to do this is reassigning, e.g.
x = 1
. It is not you are looking for, isn't it? So, you need to clarify the problem. You are probably looking for a method which allow you to get
closest odd number to the current number, aren't you?. The following is example that helps you:
>>> x = 839120938198492 839120938198492 >>> x.to_bytes(10, byteorder='big') b'\x00\x00\x00\x02\xfb-\x11q\xe5\xdc' >>> z=x.to_bytes(10, byteorder='big') >>> z b'\x00\x00\x00\x02\xfb-\x11q\xe5\xdc' >>> int.from_bytes(z, byteorder='big') 839120938198492 >>> closest_odd = z[:-1] + (z[-1] - 1 if z[-1] % 2==0 and z[-1] - 1 > 0 else z[-1] + 1).to_bytes(1, byteorder='big') >>> int.from_bytes(closest_odd, byteorder='big') 839120938198491