Bottom Page

Thread Rating:
  • 1 Vote(s) - 4 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 convert hex encoded string to ASCII
#1
given a string of hexadecimal characters that represent ASCII characters, i want to convert it to those ASCII characters.  for example:

'707974686f6e2d666f72756d2e696f' -> 'python-forum.io'

in python 2 i can do .decode('hex') but this is gone in python3. so, i found this:
codecs.decode(codecs.decode('707974686f6e2d666f72756d2e696f','hex'),'ascii')
anything simpler that works in either python 2 or python 3 ?
What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Quote
#2
How about
codecs.decode("707974686f6e2d666f72756d2e696f", "hex")
Does it give the result you want?
Quote
#3
Personally, I've found the fromhex method of bytes to be useful.

print(bytes.fromhex('7370616d'))    # b'spam'
Quote
#4
(Sep-29-2016, 07:45 AM)j.crater Wrote: How about
codecs.decode("707974686f6e2d666f72756d2e696f", "hex")
Does it give the result you want?

not in py 3.  i want an ASCII or UTF-8 string, not an array of bytes. this why i added the 2nd call to codecs.decode(,"ascii").
What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Quote
#5
Quote:this why i added the 2nd call to codecs.decode(,"ascii")
You don't need a second call,just add .decode('utf-8').
>>> codecs.decode("707974686f6e2d666f72756d2e696f", "hex").decode('utf-8')
'python-forum.io'
It will work the same in Python 2.x
>>> codecs.decode("707974686f6e2d666f72756d2e696f", "hex").decode('utf-8')
u'python-forum.io'
Strings are Unicode by default in Python 3.x.
>>> u'python-forum.io' == 'python-forum.io'
True
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Error in the code ->ValueError: could not convert string to float: ' ' eagleboom 1 170 Nov-29-2019, 06:19 AM
Last Post: ThomasL
  Trouble with encoded data (I think) fishglue 0 118 Oct-10-2019, 08:15 PM
Last Post: fishglue
  convert integers to a string tantony 1 191 Oct-04-2019, 06:40 PM
Last Post: ichabod801
  Doing calculation with ascii file Mike 5 224 Oct-02-2019, 02:16 PM
Last Post: Mike
  ValueError: could not convert string to float: . BoaCoder3 3 76,208 Aug-24-2019, 06:26 AM
Last Post: atlass218
  ValueError: could not convert string to float michaelbs007 1 2,259 Jun-08-2019, 08:44 PM
Last Post: micseydel
  Read ASCII File pyth0nus3r 3 538 May-23-2019, 11:13 PM
Last Post: michalmonday
  convert a string into an int in Python anjita 2 879 Jan-18-2019, 10:37 AM
Last Post: sandeepatel
  convert non-string with explicit base jacklee26 5 2,753 Nov-06-2018, 06:50 AM
Last Post: jacklee26
  Convert .csv string into float YOYOYO 1 2,339 Apr-25-2018, 12:15 PM
Last Post: buran

Forum Jump:


Users browsing this thread: 3 Guest(s)