Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

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 ?

question from:https://stackoverflow.com/questions/45233355/convert-a-byte-array-to-string

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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> 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...