1

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?

2 Answers 2

4

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.

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

1 Comment

If this is a signed short then I believe a slight change is needed: (hi << 8 | (0x00ff & lo)
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.