Bob
Bob

Reputation: 9

Python: Need help converting a string of hex values into numpy array

I am very much a Python beginner using Thonny and Python 3.7.7. I have strings of values that I want to convert to integers and put in a numpy array. A typical string:

print(temp)
05:01:00016043:00002F4F:00002F53:00004231:000050AA:00003ACE:00005C44:00003D3B:000064BC

temp = temp.split(":")
print(temp)

['05', '01', '00016043', '00002F4F', '00002F53', '00004231', '000050AA', '00003ACE', '00005C44', '00003D3B', '000064BC']

I want to efficiently turn this list of strings describing hexadecimal numbers into integers and put them into an numpy array (with the emphasis on efficiently!).

a = np.array([11], dtype=int)

Any suggestions? Thanks

Upvotes: 1

Views: 783

Answers (2)

Alex Galarce
Alex Galarce

Reputation: 31

How about a nice and tidy one-line list comprehension? For a string s:

np.array([int(hexa, base=16) for hexa in s.split(sep=":")])

This may look complicated, but the output of s.split(sep=":") is a list of string hexadecimals. Passing each one of them (each hexa) into int with base=16 converts them, as you'd like.

Upvotes: 2

Gilseung Ahn
Gilseung Ahn

Reputation: 2624

Apply function which converts x to int(x, 16) to every element in L

import pandas as pd
import numpy as np

L = ['05', '01', '00016043', '00002F4F', '00002F53', '00004231', '000050AA', '00003ACE', '00005C44', '00003D3B', '000064BC']
output = pd.Series(L).apply(lambda x:int(x, 16)).values
print(output)

output is

[    5     1 90179 12111 12115 16945 20650 15054 23620 15675 25788]

Upvotes: 1

Related Questions