1

I have a scenario where in based on a given String I need to return an integer value. I am hashing String to a byte array . Now since my Integer range is 0-999 which can be represented by 2bytes, I am hoping to use last two bytes of the byte array to convert to integer . But I am not getting the correct result

I have tried using Byte buffer wrap method , defining offset as length-3 and defining the length as 2

ByteBuffer.wrap(bytes,bytes.length-3,2).getInt()

I am expecting an Integer data based on the last two bytes of the array but getting Exception in thread "main" java.nio.BufferUnderflowException

2
  • Why length-3 and not length-2? Commented Apr 25, 2019 at 15:56
  • The last two bytes are at length-2 and length-1. Commented Apr 25, 2019 at 16:02

1 Answer 1

3

ByteBuffer#getInt reads 4 bytes starting at the current position, however your wrapped ByteBuffer has a remaining size (limit - position) of 2, hence it throws a BufferUnderflowException. Instead, you should use ByteBuffer#getShort, which can be stored in an int.

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

2 Comments

Good answer. A minor and off-topic nitpick: brians.wsu.edu/2016/05/19/hence-why
@DodgyCodeException Thanks for the tip!

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.