Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala way for converting Long to ArrayByte

Tags:

arrays

scala

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()
like image 729
sbb Avatar asked Oct 21 '25 14:10

sbb


1 Answers

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
like image 125
Federico Pellegatta Avatar answered Oct 23 '25 05:10

Federico Pellegatta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!