[英]convert numpy array type: float32 to char
I need to convert a numpy array of type float32 into char in a way that each 4 consecutive members form a float number. 我需要将float32类型的numpy数组转换为char,以使每个4个连续成员形成一个浮点数。 so the resulting array should have a length 4 times the original. 因此结果数组的长度应为原始数组的4倍。 How can I do that? 我怎样才能做到这一点?
You could try numpy.ndarray.tostring . 您可以尝试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. 在我的机器上,浮点类型是64位双精度型,因此x
的长度为10, s
的长度为80。如果打算与其他计算机共享字符串,请记住字节顺序 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.