0

Following the similar question, I am trying to implement the unpack method in Java for Integer:

Sample byte array input: chunkByte[1219:1240] = [64, 30, 31, 0, 64, 118, 31, 0, 64, -22, 29, 0, 64, 4, 30, 0, 64, 26, 36, 0, 64] where

Code in Python:

    fid = open(raw_file, 'rb')
    fid.seek(0, os.SEEK_END)
    nFileLen = fid.tell()
    fid.seek(0, 0)
    
    chunk_size = 2 ** 19
    n = int(nFileLen / chunk_size)

    for i in range(0, n):
        nLenVals = round(chunk_size / 4)
        vals = struct.unpack('I' * nLenVals, fid.read(chunk_size))

In Java:

vals = (int[]) unpack('I', chunk_size / 4, chunkByte);

where

    private Object unpack(char type, int dim, byte[] chunkByte) {
        if (type == 'f') {
            var floats = ByteBuffer.wrap(chunkByte).order(ByteOrder.LITTLE_ENDIAN).asFloatBuffer();
            var floatArray = new float[dim];
            floats.get(floatArray);
            return floatArray;
        } else if (type == 'I') {
            var ints = ByteBuffer.wrap(chunkByte).order(ByteOrder.nativeOrder()).asIntBuffer();
            var intArray = new int[dim];
            ints.get(intArray);
            return intArray;
        }
        return null;
    }

I get negative results for the same byte arrays (byte[] chunkByte).

For example, in Python, I get this value: vals[1220]=3221234265. But I get the wrong value for the similar index: vals[1220]=-1073733031.

I tried changing nativeOrder() to LITTLE_ENDIAN but it didn't help.

newbie5050
  • 51
  • 6
  • Please show a [mcve], including but not limited to, what are the contents of the byte array you are trying to unpack? What are the expected results? What is the actual result? Please show a *minimal* example that reproduces the problem, and not the thousands of bytes that you are actually using. – Sweeper Jun 27 '23 at 03:57
  • thanks @ Sweeper but how can I submit the byte array here? – newbie5050 Jun 27 '23 at 04:00
  • 1
    Actually never mind. 3221234265 is the unsigned value of -1073733031. There are no unsigned integers in Java, but you can use `Integer.toUnsignedLong` to convert it to a `long`. See [this](https://stackoverflow.com/questions/9854166/declaring-an-unsigned-int-in-java) for more info. – Sweeper Jun 27 '23 at 04:08
  • @ Sweeper. Do you mean converting negative integers to Integer.toUnsignedLong? – newbie5050 Jun 27 '23 at 04:13
  • You can use that with all integers, not just negative ones. It converts all `int`s to non-negative `long`s. – Sweeper Jun 27 '23 at 04:15
  • @Sweeper. Thanks, it worked! Is there any way to convert all integers without a for-loop iteration? – newbie5050 Jun 27 '23 at 04:18
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/254260/discussion-between-newbie5050-and-sweeper). – newbie5050 Jun 27 '23 at 04:19

0 Answers0