hardier
hardier

Reputation: 85

How to convert a Byte Array to Short Array in scala?

I have a byte array and want to convert it into short array, say input: [1, 2, 3, 4] output: [0x102, 0x304]

Is there any method to call?

Upvotes: 1

Views: 1105

Answers (2)

0__
0__

Reputation: 67280

The grouped(2).map approach of Peter Neyens is what I would do, although just using simply bitshift instead of all the effort to go through a ByteBuffer:

def convert(in: Array[Byte]): Array[Short] = 
  in.grouped(2).map { case Array(hi, lo) => (hi << 8 | lo).toShort } .toArray

val in  = Array(1.toByte, 2.toByte, 3.toByte, 4.toByte)
val out = convert(in)
out.map(x => s"0x${x.toHexString}") // 0x102, 0x304

If your input might have an odd size, use an extra case in the pattern match as in Peter's answer.

Upvotes: 4

Peter Neyens
Peter Neyens

Reputation: 9820

You can use the toShort method of Byte:

val bytes = Array[Byte](1, 2, 3, 4, 192.toByte)
bytes: Array[Byte] = Array(1, 2, 3, 4, -64)
bytes.map(_.toShort)
res1: Array[Short] = Array(1, 2, 3, 4, -64)

I see you want to combine two Bytes into one Short :

import java.nio.{ByteBuffer, ByteOrder}

def bytesToShort(byte1: Byte, byte2: Byte) : Short = {
  ByteBuffer
    .allocate(2)
    .order(ByteOrder.LITTLE_ENDIAN)
    .put(byte1)
    .put(byte2)
    .getShort(0)
}

val bytes = Array[Byte](1, 2, 3, 4)
bytes.grouped(2).map {
  case Array(one) => bytesToShort(one, 0.toByte)
  case Array(one, two) => bytesToShort(one, two)
}.toArray

Upvotes: 0

Related Questions