Timmy
Timmy

Reputation: 12828

How do I convert an array of longs to bytes in Scala?

I want to md5 an Array[Long], so I would like to make that an Array[Byte] because the MD5 function takes an Array[Byte], how can I do that?

I use messagedigest for this.

Upvotes: 4

Views: 688

Answers (1)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340708

Using ByteBuffer:

val arr = listOfLongs.
  foldLeft(ByteBuffer.allocate(8 * listOfLongs.size)){ (buffer, lon) => 
    buffer putLong lon
  }.array

Or more imperatively:

val buffer = ByteBuffer.allocate(8 * listOfLongs.size)
listOfLongs.foreach(buffer putLong _)
val arr = buffer.array

Note: if you need little-endian, just call:

buffer.order(java.nio.ByteOrder.LITTLE_ENDIAN)

at the beginning. Fore more inspiration: Convert long to byte array and add it to another array.

Upvotes: 6

Related Questions