1
array([(1, 1, 0, 2, 240), (1, 1, 0, 255, 255), (1, 1, 0, 255, 255), ...,
       (1, 1, 0, 255, 255), (1, 1, 0, 255, 255), (1, 1, 0, 255, 60)],
      dtype=[('A','u1'), ('B','u1'), ('C','u1'), ('D','u1'), ('E','u1')])

I have a numpy array as shown above and I want to print them to a file in HEX like so:

1 1 0 02 EF
1 1 0 FF FF
...
1 1 0 FF FF
1 1 0 FF 3C

The integer values of the left most 3 columns are only 0 and 1 so they should only have 1 HEX characters. The rightmost 2 columns both should have 2 HEX characters even if their integer value requires only 1. The "0x" prefix should be omitted.

The straightforward way is to use for loop and format the strings but the data set is huge and it takes a very long time to complete. Is there a fast numpy way to do build the string array and then output it to file?

2
  • It will be way easier to do that if your data where stored as a 2D array and not as a structured arrays, why are you using a structured array since you do not have mixed datatype ? Commented Apr 22, 2021 at 10:51
  • The data is read in from a binary file into a structured array. The data fields in the binary file have different lengths. How do I read in the data from the binary file into 2D array instead of structured array? Commented Apr 22, 2021 at 11:01

1 Answer 1

1

Ok I did some more work on this and I found this solution that worked for me:

numpy.savetxt("my_file.txt", my_numpy_structured_array, delimiter=" ", fmt="%x %x %x %02x %02x")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.