2

I need to get 64-bit little-endian integer as byte-array with upper 32 bits zeroed and lower 32 bits containing some integer number, let say it's 51.

Now I was doing it in this way:

 byte[] header = ByteBuffer
            .allocate(8)
            .order(ByteOrder.LITTLE_ENDIAN)
            .putInt(51)
            .array();

But I'm not sure is it the right way. Am I doing it right?

4
  • 2
    Why do you expect there to be 64 bits in an int? An int is 32 bits. Moreover, ByteBuffer.allocate takes a number of bytes, not a number of bits, so your ByteBuffer has sixty zero bytes at the end. Commented Feb 22, 2016 at 18:32
  • I just quoted what I have in API description. It says "64 bit Little-Endian integer, upper 32 bits are reserved for flags (zeroed), lower 32 bits represent the size of the upcoming data". And thanks, it's really my mistake to allocate 64 BYTES instead of bits. Commented Feb 22, 2016 at 18:36
  • You may want to use a long if you want to be able to represent 32 bits indicating a positive number such as a size (of course you may be able to indicate all possible sizes using 31 bits as well). Commented Feb 22, 2016 at 18:44
  • Code edited to fix allocation wrong value. Commented Feb 22, 2016 at 22:35

1 Answer 1

3

What about trying the following:

private static byte[] encodeHeader(long size) {
    if (size < 0 || size >= (1L << Integer.SIZE)) {
        throw new IllegalArgumentException("size negative or larger than 32 bits: " + size);
    }

    byte[] header = ByteBuffer
            .allocate(Long.BYTES)
            .order(ByteOrder.LITTLE_ENDIAN)
            .putInt((int) size)
            .array();
    return header;
}

Personally this I think it's even more clear and you can use the full 32 bits.

I'm disregarding the flags here, you could pass those separately. I've changed the answer in such a way that the position of the buffer is placed at the end of the size.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.