Gооd_Mаn
Gооd_Mаn

Reputation: 1088

Convert ASCII string encoded array into string?

Input:

'0x0 0x48 0x65 0x6c 0x6c 0x6f 0x8E 0x21'

Output:

Hello!

Current Solution:

    s = []
    birary_data = '0x0 0x48 0x65 0x6c 0x6c 0x6f 0x8E 0x21'.replace(' ', '').split('0x')
    for c in birary_data:
        if len(c) > 1:
            s.append(bytes.fromhex(c).decode('utf-8', 'ignore'))
    print("".join(s))

Need help with:

Could anyone suggest a more elegant solution, please?

Upvotes: 3

Views: 462

Answers (5)

Guy
Guy

Reputation: 50819

Another option is to remove 3 characters (or less) length substrings, 0x and white spaces. bytes.fromhex can handle a string like '48656c6c6f8E21'

binary_data = '0X0 0x48 0x65 0x6c 0x6c 0x6f 0x8E 0x21'
binary_data = re.sub(r'\b\w{3}\b|\s?0x', '', binary_data)
print(bytes.fromhex(binary_data).decode('utf-8', 'ignore'))

Upvotes: 4

Jon Betts
Jon Betts

Reputation: 3328

The builtin bytes.fromhex() is very nearly all we need. There are however two problems we need to get around:

  • The null byte at the front
  • The invalid char in position 6 (0x8E)
import re

data = '0x0 0x48 0x65 0x6c 0x6c 0x6f 0x8E 0x21'

string = bytes.fromhex(re.sub('0x(0 )?', '', data)).decode('utf-8', 'ignore')

The regex will take care of both stripping the null byte and formatting the string correctly for bytes.fromhex(). The ignore in the decode will skip the bad byte.

Upvotes: 3

Joan Lara
Joan Lara

Reputation: 1396

birary_data = '0x0 0x48 0x65 0x6c 0x6c 0x6f 0x8E 0x21'.replace('0x', '').split()
print(bytearray.fromhex(''.join(c for c in birary_data if len(c) > 1)).decode('utf-8', 'ignore'))

Output:

Hello!

Upvotes: 2

Akhil Pathania
Akhil Pathania

Reputation: 752

You can use the below one Here in the code i am first splitting the hex according to white-space and then iterating and joining the character i get.

a = '0x0 0x48 0x65 0x6c 0x6c 0x6f 0x8E 0x21'
print(''.join(chr(int(i, 16)) for i in a.split()))

Upvotes: 3

Shubham Sharma
Shubham Sharma

Reputation: 71689

Try this:

data = '0x0 0x48 0x65 0x6c 0x6c 0x6f 0x8E 0x21'
string = "".join([chr(int(item, 16)) for item in data.split()])
print(string)

Output:

Hello!

Upvotes: 4

Related Questions