0

I am trying to convert a long number (convertex from Hex to Long) to a byte array. I'm trying the following code:

    ByteBuffer b = ByteBuffer.allocate(4);
    // The literal 4328719365 of type int is out of range 
    b.putLong(4328719365);
    byte[] result = b.array();

but it's not compiling due to being out of range for int.

What can I do to solve this issue?

3
  • 6
    b.putLong(4328719365L); Note L. And keep in mind, that long takes 8 bytes :) Commented Oct 12, 2019 at 11:31
  • @kofemann Exception in thread "main" java.nio.BufferOverflowException Commented Oct 12, 2019 at 11:33
  • @Harold: Probably because a long needs 8 bytes and your buffer only has allocated 4. Commented Oct 12, 2019 at 11:34

2 Answers 2

1

Suffix L (or l) converts literal number to a long.

So try this:

b.putLong(4328719365L);

You can use literal long value just like number without L suffix. Like assign them to variables:

long myLongValue = 4328719365L;
b.putLong(myLongValue);

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

3 Comments

Note that L is considered by some to be preferable, because l looks a lot like 1 in some fonts.
Thanks. But how do I put it with a variable name? Like b.putLong(longL);
@Harold you don't need to do it with a variable: you simply declare the variable as long. It's only literals where you need to use the L.
0

1) Suffix L to the value 2) Increase the ByteBuffer allocated size and try 3) Int will take max of 10 digits and putLong might internally add L and making it beyond 10. Please check reducing digits in number.

1 Comment

putLong will not write a String representation in decimal digits. And definitely not add an L at. the end. It writes the raw binary value.