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
#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


Messages In This Thread
Convert even byte array to odd - by medatib531 - Mar-17-2020, 02:18 AM
RE: Convert even byte array to odd - by scidam - Mar-17-2020, 02:48 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Convert numpy array to image without loading it into RAM. DreamingInsanity 7 5,917 Feb-08-2024, 09:38 AM
Last Post: paul18fr
  Convert np Array A to networkx G IanAnderson 2 698 Jul-05-2023, 11:42 AM
Last Post: IanAnderson
  extract only text strip byte array Pir8Radio 7 3,004 Nov-29-2022, 10:24 PM
Last Post: Pir8Radio
  Convert String of an int array to a Numpy array of ints mdsousa 5 5,712 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,618 Sep-18-2020, 10:10 PM
Last Post: tienttt
  convert array of numbers to byte array adetheheat 3 2,823 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,741 Feb-08-2020, 06:58 PM
Last Post: karkas
  convert a json file to a python dictionnary of array Reims 2 2,263 Sep-10-2019, 01:08 PM
Last Post: Reims
  Byte array is sorted when sending via USB daviddlc68 1 2,844 Aug-16-2019, 10:11 AM
Last Post: wavic
  Reading data from serial port as byte array vlad93 1 12,094 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