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 ?
-
1Try to parse each number as a char and concate them to have a stringQuentin– Quentin2017-07-21 08:58:37 +00:00Commented Jul 21, 2017 at 8:58
-
Converting byte array to stringSameera.San– Sameera.San2017-07-21 09:06:40 +00:00Commented Jul 21, 2017 at 9:06
-
2Possible duplicate of Byte array to String and back.. issues with -127Alexander Azarov– Alexander Azarov2017-07-21 09:35:57 +00:00Commented Jul 21, 2017 at 9:35
3 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.
3 Comments
(bytes.map(_.toChar)).mkString or new String(bytes)?A is represented by 65 in both) but most (maybe all?) other characters with multiple bytes. In short; they're the same if your string contains only ASCII characters but otherwise will produce different results.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>
3 Comments
val msg = Array[Byte](-17, -69, -65, 72, 101, 108, 108, 111) (msg.map(_.toChar)).mkString You would get something that looked very weird and not the expected "Hello" that you would get from this: new String(msg)println("🍕".getBytes(StandardCharsets.UTF_8).length) > 4The 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.
1 Comment
bytes.mkString(" ")? and 2-This answer is out of place. It doesn't answer the question asked.