Python Forum
converting binary b'0x31303032\n' to "1002" string
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
converting binary b'0x31303032\n' to "1002" string
#1
I've tried so many things for hours with out success. Help would be so greatly appreciated.
I need to convert the binary type b'0x31303032\n' to "1002" string, which is the hexidecimal translation of 0x31303032
Reply
#2
You can use binascii:
import binascii

x = b'0x31303032\n'
x1 = binascii.unhexlify(x.strip()[2:]).decode()
print(x1)
results:
Output:
1002
I should explain a bit:
binascii.unhexlify(hexstr)

Return the binary data represented by the hexadecimal string hexstr. This function is the inverse of b2a_hex(). hexstr must contain an even number of hexadecimal digits (which can be upper or lower case), otherwise an Error exception is raised.

x.strip() removes the line feed
the [2:] slices off the 0x
the decode() at the end flips from bytes
Reply
#3
THANK YOU!
I was so close yet so far. Excellent work.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Add one to binary string uwl 2 884 Sep-11-2022, 05:36 PM
Last Post: uwl
  Converting '1a2b3c' string to Dictionary PythonNoobLvl1 6 1,780 May-13-2022, 03:44 PM
Last Post: deanhystad
  Converting an RGBA image to Grayscale and Binary Joni_Engr 3 4,561 Aug-23-2021, 11:54 AM
Last Post: Pedroski55
  Need help converting string to int dedesssse 7 2,616 Jul-07-2021, 09:32 PM
Last Post: deanhystad
  Beautify dictionary without converting to string. sharoon 6 3,297 Apr-11-2021, 08:32 AM
Last Post: buran
  how to deal with problem of converting string to int usthbstar 1 1,932 Jan-05-2021, 01:33 PM
Last Post: perfringo
  [HELP] string into binary ZeroPy 2 2,024 Dec-31-2020, 08:15 PM
Last Post: deanhystad
  Converting string to hex triplet menator01 4 4,218 Aug-03-2020, 01:00 PM
Last Post: deanhystad
  converting string object inside a list into an intiger bwdu 4 2,553 Mar-31-2020, 10:36 AM
Last Post: buran
  Converting query string as a condition for filter data. shah_entrance 1 1,751 Jan-14-2020, 09:22 AM
Last Post: perfringo

Forum Jump:

User Panel Messages

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