convert a byte array to string convert a byte array to string arrays arrays

convert a byte array to string


You can always convert the byte array to a string if you know its charset,

val str = new String(bytes, StandardCharsets.UTF_8)

And the default Charset would used if you don't specify any.


You could convert the byte array to a char array, and then construct a string from that

scala> val bytes = Array[Byte]('a','b','c','d')bytes: Array[Byte] = Array(97, 98, 99, 100)scala> (bytes.map(_.toChar)).mkString res10: String = abcdscala> 


The bytes to string function I was looking for was where each byte was just a numeric value represented as a string, without any implied encoding. Thanks to the suggestions supplied here, I ended up with the following function which works for my purposes. I post it here incase it useful to someone else.

  def showBytes(bytes: Array[Byte]):String = {    bytes.map(b => "" + b.toInt).mkString(" ")  }

This function will return a string containing numeric values separated by spaces.