Python Forum
Convert even byte array to odd
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Convert even byte array to odd
#1
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?
Reply
#2
(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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Convert numpy array to image without loading it into RAM. DreamingInsanity 7 5,722 Feb-08-2024, 09:38 AM
Last Post: paul18fr
  Convert np Array A to networkx G IanAnderson 2 625 Jul-05-2023, 11:42 AM
Last Post: IanAnderson
  extract only text strip byte array Pir8Radio 7 2,787 Nov-29-2022, 10:24 PM
Last Post: Pir8Radio
  Convert String of an int array to a Numpy array of ints mdsousa 5 5,575 Apr-08-2021, 08:00 PM
Last Post: mdsousa
  'utf-8' codec can't decode byte 0xe2 in position 122031: invalid continuation byte tienttt 12 11,344 Sep-18-2020, 10:10 PM
Last Post: tienttt
  convert array of numbers to byte array adetheheat 3 2,727 Aug-13-2020, 05:09 PM
Last Post: bowlofred
  'utf-8' codec can't decode byte 0xda in position 184: invalid continuation byte karkas 8 31,468 Feb-08-2020, 06:58 PM
Last Post: karkas
  convert a json file to a python dictionnary of array Reims 2 2,201 Sep-10-2019, 01:08 PM
Last Post: Reims
  Byte array is sorted when sending via USB daviddlc68 1 2,775 Aug-16-2019, 10:11 AM
Last Post: wavic
  Reading data from serial port as byte array vlad93 1 11,978 May-18-2019, 05:26 AM
Last Post: heiner55

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020