Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert a byte array to string

My Scala code received a binary from byte stream,it looks like [61 62 63 64].The content is "abcd". I use toString to convert it p, but failed. How do I print it as string ?

like image 405
Robin Avatar asked Jul 21 '17 08:07

Robin


2 Answers

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.

like image 76
Sleiman Jneidi Avatar answered Oct 22 '22 22:10

Sleiman Jneidi


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 = abcd

scala> 
like image 32
cms Avatar answered Oct 22 '22 22:10

cms