Am1rr3zA
Am1rr3zA

Reputation: 7421

Java equivalent of struct.unpack('d', s.decode('hex'))[0]

I am reading a file which is stored binaries. In python I can decode the file easily

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

Now I want to do the same decoding in Java, do we have anything similar?

Upvotes: 2

Views: 1110

Answers (1)

Andreas
Andreas

Reputation: 159165

Since those bytes are in Little-Endian order, being C code on an Intel processor, use ByteBuffer to help flip the bytes:

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

Here I'm using Long.parseUnsignedLong(s, 16) as a quick way to do the decode('hex') for 8 bytes.


If data is already a byte array, do this:

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

Imports for the above are:

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

Upvotes: 7

Related Questions