gpt4 book ai didi

Java 相当于 struct.unpack ('d' 、 s.decode ('hex' ))[0]

转载 作者:行者123 更新时间:2023-12-02 02:18:09 25 4
gpt4 key购买 nike

我正在读取一个存储二进制文件的文件。在 python 中我可以轻松解码文件

>>> s = '0000000000A0A240'
>>> s.decode('hex')
'\x00\x00\x00\x00\x00\xa0\xa2@'
>>> import struct
>>> struct.unpack('d', s.decode('hex'))[0]
2384.0

现在我想在 Java 中进行相同的解码,我们有类似的东西吗?

最佳答案

由于这些字节采用 Little-Endian 顺序,是 Intel 处理器上的 C 代码,因此使用 ByteBuffer 来帮助翻转字节:

String s = "0000000000A0A240";
double d = ByteBuffer.allocate(8)
.putLong(Long.parseUnsignedLong(s, 16))
.flip()
.order(ByteOrder.LITTLE_ENDIAN)
.getDouble();
System.out.println(d); // prints 2384.0

在这里,我使用 Long.parseUnsignedLong(s, 16) 作为对 8 个字节进行 decode('hex') 的快速方法。

<小时/>

如果数据已经是字节数组,请执行以下操作:

byte[] b = { 0x00, 0x00, 0x00, 0x00, 0x00, (byte) 0xA0, (byte) 0xA2, 0x40 };
double d = ByteBuffer.wrap(b)
.order(ByteOrder.LITTLE_ENDIAN)
.getDouble();
System.out.println(d); // prints 2384.0

上述导入内容为:

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

关于Java 相当于 struct.unpack ('d' 、 s.decode ('hex' ))[0],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48957165/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com