1

I have a binary file written as

16b-Real (little endian, 2s compliment)
16b-Imag (little endian, 2s compliment)
.....repeating

I need to convert it to a 1D array of complex numbers. Can't figure out how to combine the "tuples or lists" into a single value

import numpy as np
dtype = np.dtype([('i','<i2'), ('q','<i2')])
array = np.fromfile(data_file, dtype=dtype)
print(array)
el = array[0]
print(el)
print(type(el))

Output:

[(531, -660) (267, -801) (-36, -841) ... (835, -102) (750, -396)
 (567, -628)]
(531, -660)
<class 'numpy.void'>

Hoping for output:

[531-660j, 267-801j,...]
3
  • can you give us an example of actual input (and not just the format?) I'm not sure I fully understand the format of your input, which may be a part of the problem. Commented Jul 17, 2019 at 19:52
  • What was the problem with complex(re, im)? Commented Jul 17, 2019 at 19:53
  • Input binary data from hex editor grouped by bytes: 13 02 6C FD 0B 01 DF FC. Which when grouped by word looks like: 0213 FD6C 010B FCDF. In decimal: 531 -660 267 -801 Commented Jul 17, 2019 at 19:58

2 Answers 2

3

You can convert each tuple to a complex number while iterating over the list of tuples

array = [(531, -660), (267, -801), (-36, -841) ,(835, -102) ,(750, -396), (567, -628)]

#Iterate over each element and convert it to complex
array = [complex(*item) for item in array]

print(array)
print(type(array[0]))

The output will be

[(531-660j), (267-801j), (-36-841j), (835-102j), (750-396j), (567-628j)]
<class 'complex'>
Sign up to request clarification or add additional context in comments.

Comments

1

So you have loaded the file as a structured array with 2 integer fields:

In [71]: dtype = np.dtype([('i','<i2'), ('q','<i2')])                                                        
In [72]: arr = np.array([(531, -660), (267, -801), (-36, -841), (835, -102), (750, -396)], dtype)            
In [73]: arr                                                                                                 
Out[73]: 
array([(531, -660), (267, -801), (-36, -841), (835, -102), (750, -396)],
      dtype=[('i', '<i2'), ('q', '<i2')])

We can add the two fields with the appropriate 1j multiplier to make a complex array:

In [74]: x=arr['i']+1j*arr['q']                                                                              
In [75]: x                                                                                                   
Out[75]: array([531.-660.j, 267.-801.j, -36.-841.j, 835.-102.j, 750.-396.j])

If I'm not mistaken, numpy only implements float complex (64 and 128 bit), so probably have go through this <i2 stage.

Comments

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.