4

I'm trying to convert the Long to array byte. This code block is working but this solution is a Java solution. I'm looking for a good solution in Scala. How can I convert the Long to array byte in Scala way?

val arrayByteFromLong: Array[Byte] = ByteBuffer.allocate(8).putLong(myLong).array()
1
  • 2
    It's perfectly fine for Scala too (I'd prefer it to Federico's answer). One exception is if you are looking for code which will work in Scala.js/Scala Native. Commented Apr 8, 2017 at 13:07

1 Answer 1

5

You can leverage scala.math.BigInt:

import scala.math.BigInt

val arrayByteFromLong: Array[Byte] = BigInt(myLong).toByteArray

If you want to also pad the array to 8 Bytes you can do (quick-and-dirty not so efficient version):

arrayByteFromLong.reverse.padTo(8,0).reverse
Sign up to request clarification or add additional context in comments.

2 Comments

Just as easy to get back via BigInt(arrayByteFromLong).toLong
note that BigInt.toByteArray and ButeBuffer have different padding rules: BigInt(-4227595774L).toByteArray => Array(-1, 4, 4, 2, 2) ByteBuffer.allocate(8).putLong(-4227595774L).array() => Array[Byte] = Array(-1, -1, -1, -1, 4, 4, 2, 2)

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.