convert a byte array to string

一曲冷凌霜 提交于 2019-12-06 16:50:58

问题


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 ?


回答1:


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> 



回答2:


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.



来源:https://stackoverflow.com/questions/45233355/convert-a-byte-array-to-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!