Java 如何在python中将字节数组转换为双精度数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20530678/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I convert a byte array to a double in python?
提问by user2426316
I am using Java to convert a double into a byte array. Like this:
我正在使用 Java 将双精度转换为字节数组。像这样:
public static byte[] toByteArray(double value) {
byte[] bytes = new byte[8];
ByteBuffer.wrap(bytes).putDouble(value);
return bytes;
}
Now, I would like to convert this byte array back into a double. In Java I would do it like this:
现在,我想将此字节数组转换回双精度。在 Java 中,我会这样做:
public static double toDouble(byte[] bytes) {
return ByteBuffer.wrap(bytes).getDouble();
}
Now, how can I write the toDouble()
method in Python?
现在,我如何toDouble()
在 Python 中编写该方法?
采纳答案by Martijn Pieters
Python has the struct
moduleto convert bytes back to float
values:
Python 具有将字节转换回值的struct
模块float
:
import struct
value = struct.unpack('d', bytes)[0]
Here 'd'
signifies that a double value is expected (in native endianess, as 8 bytes). See the module documentation for more options, including specifying endianess.
这里'd'
表示需要一个双精度值(在本机字节序中,为 8 个字节)。有关更多选项,包括指定字节顺序,请参阅模块文档。
Another option is to turn your bytes
value into an array
object; you'd use this is if you had a homogenous sequence of doubles:
另一种选择是将您的bytes
价值变成一个array
对象;如果你有一个同构的双打序列,你会使用这个:
import array
doubles_sequence = array.array('d', bytes)
where every 8 bytes is interpreted as a double value, making doubles_sequence
a sequence of doubles, addressable by index. To support a different endianess, you can swap the byte order with doubles_sequence.byteswap()
.
其中每 8 个字节被解释为一个双doubles_sequence
精度值,形成一个双精度序列,可通过索引寻址。要支持不同的字节序,您可以将字节顺序与doubles_sequence.byteswap()
.
回答by abarnert
You want the struct
module:
你想要的struct
模块:
>>> d = 1.234
>>> b = struct.pack('d', d)
>>> b
b'X9\xb4\xc8v\xbe\xf3?'
>>> d2, = struct.unpack('d', b)
>>> d2
1.234
The pack
method gives you a bytes
in Python 3.x, or a str
in Python 2.x. This type isn't mutable like a Java byte[]
, and in 2.x it also acts like a sequence of single-character strings, not a sequence of numbers from 0-255. If you need to fix either of those, just convert it to bytearray
.
该pack
方法bytes
在 Python 3.x 中为您提供了一个,或者str
在 Python 2.x 中为您提供了一个。这种类型不像 Java 那样可变byte[]
,在 2.x 中它也像一个单字符串序列,而不是从 0 到 255 的数字序列。如果您需要修复其中任何一个,只需将其转换为bytearray
.
Also, note that—in both Java and Python—you probably want to specify an explicit endianness more often than not, especially if you're planning to save the bytes to a file or send them over the network. See Format Stringsfor details.
另外,请注意,在 Java 和 Python 中,您可能希望经常指定显式字节序,尤其是在您计划将字节保存到文件或通过网络发送它们时。有关详细信息,请参阅格式字符串。
So:
所以:
>>> b = bytearray(struct.pack('!d', d))
>>> b
bytearray(b'?\xf3\xbev\xc8\xb49X')
>>> b[0]
63