Scala hex string to bytes

Since the title of the question doesn't mention Protobuf, if anyone is looking for a solution that doesn't require any dependencies for converting a hex String to Seq[Byte] for any sized array: (don't forget to add input validation as necessarily)

val zeroChar: Byte = '0'.toByte
val aChar: Byte = 'a'.toByte

def toHex(bytes: Seq[Byte]): String = bytes.map(b => f"$b%02x").mkString

def toBytes(hex: String): Seq[Byte] = {

  val lowerHex = hex.toLowerCase

  val (result: Array[Byte], startOffset: Int) =
    if (lowerHex.length % 2 == 1) {

    // Odd
    val r = new Array[Byte]((lowerHex.length >> 1) + 1)
    r(0) = toNum(lowerHex(0))
    (r, 1)

  } else {

    // Even
    (new Array[Byte](lowerHex.length >> 1), 0)
  }

  var inputIndex = startOffset
  var outputIndex = startOffset
  while (outputIndex < result.length) {

    val byteValue = (toNum(lowerHex(inputIndex)) * 16) +
      toNum(lowerHex(inputIndex + 1))

    result(outputIndex) = byteValue.toByte

    inputIndex += 2
    outputIndex += 1
  }

  result
}

def toNum(lowerHexChar: Char): Byte =
  (if (lowerHexChar < 'a') lowerHexChar.toByte - zeroChar else 10 +
    lowerHexChar.toByte - aChar).toByte

https://scalafiddle.io/sf/PZPHBlT/2


You can use (without additional dependencies) DatatypeConverter as:

import com.google.protobuf.ByteString
import javax.xml.bind.DatatypeConverter
val hexString: String = "87C2D268483583714CD5"
val byteString: ByteString = ByteString.copyFrom(
  DatatypeConverter.parseHexBinary(hexString)
)
val originalString = DatatypeConverter.printHexBinary(byteString.toByteArray)

You can use java.math.BigInteger to parse a String, get the Array[Byte] and from there turn it into a ByteString. Here would be the first step:

import java.math.BigInteger

val s = "f263575e7b00a977a8e9a37e08b9c215feb9bfb2f992b2b8f11e"

val bs = new BigInteger(s, 16).toByteArray

The content of bs is now:

Array(0, -14, 99, 87, 94, 123, 0, -87, 119, -88, -23, -93, 126, 8, -71, -62, 21, -2, -71, -65, -78, -7, -110, -78, -72, -15, 30)

You can then use (for example) the copyFrom method (JavaDoc here) to turn it into a ByteString.