José Fonseca
José Fonseca

Reputation: 75

Using Numpy's readtxt to read Hex numbers

I am only able to read integer values from a text file, but when I try to read integers in Hex format, an error occurs. The code line I'm using is

output = np.loadtxt(fidOut, dtype="int32", delimiter="\n");

Can you help me?

Upvotes: 5

Views: 7410

Answers (1)

deinonychusaur
deinonychusaur

Reputation: 7304

You need to add a converters so that numpy understands how to interpret the hex-data.

For a simple file test.csv with data as follows:

af,2b,10    
3aaa,4a,fa

You would need to specify converters for all three columns:

In [2]: np.loadtxt("test.csv", dtype='int32', delimiter=',', converters={_:lambda s: int(s, 16) for _ in range(3)})
Out[2]: 
array([[  175,    43,    16],
       [15018,    74,   250]], dtype=int32)

The dictionary supplied has column-index as keys and converters as values. Depending on how your hex-data is represented in the file you may need to modify the lambda-expression above.

Upvotes: 7

Related Questions