Python Forum

Full Version: Convert even byte array to odd
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello, my question is as follows:
Say I have a 256-bit array, e.g.

'74ccc1643dd3d97236bc74d378692f9617f779e6d935a6df9e8d2fe161b1fed4'
This represents a large number which is even. I want to convert this to an odd number as efficiently as possible.
My intuition is that XORing the Least Significant bit of this would be the most efficient way.
How can I do this?
(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