Matthew Lund
Matthew Lund

Reputation: 4022

Python - Parse string in "0xDE 0xAD 0xBE 0xEF" form to a bytearray

There is plenty of sample code to accomplish this in a few lines of code. Is there a library in python 3.2 that can do this in one call? If not, what's the minimum code to do this?

I'd be happy to get the results in any list-like (indexable and iterable) result...

Edit: You guys are fast! I like this one:

byte_collection = bytes(int(x, 16) for x in some_string.split())

Upvotes: 0

Views: 1441

Answers (3)

Amber
Amber

Reputation: 526763

List of integers:

list_of_ints = [int(x, 16) for x in inputstr.split()]

String of bytes (ASCII characters):

string_of_bytes = ''.join(chr(int(x, 16)) for x in inputstr.split())

In Python 3:

string_of_bytes = bytes(int(x, 16) for x in inputstr.split())

Upvotes: 3

icktoofay
icktoofay

Reputation: 129011

If you want it as a list of integers, this should work, assuming s contains your string:

[int(piece, 16) for piece in s.split()]

If you want it as a string, you can use this:

''.join(chr(int(piece, 16)) for piece in s.split())

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798784

3>> bytes(int(x, 16) for x in '0xDE 0xAD 0xBE 0xEF'.split())
b'\xde\xad\xbe\xef'

Upvotes: 3

Related Questions