1

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 1

2

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.

Sign up to request clarification or add additional context in comments.

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.