In Java, how do you convert an array of bytes to a specific primitive type, depending on the size of the array?

Ok, I'm pretty new to Java, so I apologize if this question is stupid.

I have a ByteBuffer object that contains a value that can be any number of bytes in length, with a buffer size set to length. What is the most efficient way to read a value in a buffer into the corresponding primitive type?

The code below is representative of my question.

long returnValue;
ByteBuffer bb = GetBuffer(blah);

if (bb.capacity() > 4)
{
    returnValue = (long) <how to get value from the buffer here?>
}
else if (bb.capacity() > 2)
{
    returnValue = (long) <and here...>
}
// etc...

Calling getLong () in the buffer throws an exception if the buffer limit is less than 8. Suppose I could build a long one from individual bytes, but this seems unnecessarily complicated. Is there a better way?

Thank you so much!

+3
source share
2

getLong() , 8.

, 8 . . .

, , getLong(). (. .)

long 4 , - (long) bb.getInt().

, ByteBuffer.remaining() ByteBuffer.capacity(), get long: ByteBuffer.getLong(0).

, , . ?

, . , :

import java.nio.ByteBuffer;

public class Main {

    static ByteBuffer longBuf = ByteBuffer.allocate(8);

    public static long getLong(ByteBuffer bb) {
        // Fill with eight 0-bytes and set position.
        longBuf.putLong(0, 0).position(8 - bb.remaining());

        // Put the remaining bytes from bb, and get the resulting long.
        return longBuf.put(bb).getLong(0);
    }

    public static void main(String[] args) {

        ByteBuffer bb = ByteBuffer.allocate(10);

        // Add 2 bytes
        bb.put((byte) 5);
        bb.put((byte) 7);

        // Prepare to read
        bb.flip();

        long l = getLong(bb);
        System.out.println(Long.toBinaryString(l)); // Prints 10100000111

        // Correct since, 00000101 00000111
        //               |--------|--------|
        //                       5        7
    }
}
+2

ByteBuffer get, getLong(int index):

if (bb.capacity() >= 8)
{
    returnValue = bb.getLong();
}
+2

Source: https://habr.com/ru/post/1773778/


All Articles