I need to convert a numpy array of type float32 into char in a way that each 4 consecutive members form a float number. so the resulting array should have a length 4 times the original. How can I do that?
1 Answer
You could try numpy.ndarray.tostring.
x = NP.arange(0, 10, dtype=float)
s = NP.ndarray.tostring(x)
print len(x)
print len(s)
print repr(s)
print NP.fromstring(s, dtype=float)
Output:
10
80
'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\x00@\x00\x00\x00\x00\x00\x00\x08@\x00\x00\x00\x00\x00\x00\x10@\x00\x00\x00\x00\x00\x00\x14@\x00\x00\x00\x00\x00\x00\x18@\x00\x00\x00\x00\x00\x00\x1c@\x00\x00\x00\x00\x00\x00 @\x00\x00\x00\x00\x00\x00"@'
[ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]
On my machine the float type is a 64 bit double, so the length of x is 10 and the length of s is 80. If you plan to share the string with other machines keep endianness in mind.