Skip to content

Commit dbf54bd

Browse files
cawpatCallum Gibbons
andauthored
[SCALA-508] Convert Byte Array to String in Scala (#556)
* [SCALA-508] Convert Byte Array to String in Scala * [SCALA-508] Fixed unit test errors * [SCALA-508] Fixed unit test errors * [SCALA-508] Fixed unit failure * [SCALA-508] Fixed unit failure * [SCALA-508] Changing val names --------- Co-authored-by: Callum Gibbons <[email protected]>
1 parent de084cb commit dbf54bd

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package com.baeldung.scala.strings.bytes
2+
3+
import java.nio.charset.StandardCharsets
4+
5+
object ByteArrayToString {
6+
def main(args: Array[String]): Unit = {
7+
val helloInUtf8 = Array[Byte](104, 101, 108, 108, 111)
8+
val helloInUtf16Le = Array[Byte](104, 0, 101, 0, 108, 0, 108, 0, 111, 0)
9+
10+
usingToString(helloInUtf8)
11+
usingNewString(helloInUtf8)
12+
usingToChar(helloInUtf8)
13+
usingDifferentCharSet(helloInUtf16Le)
14+
}
15+
16+
def usingToString(bytes: Array[Byte]) = {
17+
bytes.toString()
18+
}
19+
20+
def usingNewString(bytes: Array[Byte]) = {
21+
new String(bytes, StandardCharsets.UTF_8)
22+
}
23+
24+
def usingToChar(bytes: Array[Byte]) = {
25+
bytes.map(_.toChar).mkString
26+
}
27+
28+
def usingDifferentCharSet(bytes: Array[Byte]) = {
29+
new String(bytes, StandardCharsets.UTF_16LE)
30+
}
31+
32+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package com.baeldung.scala.strings.bytes
2+
3+
import com.baeldung.scala.strings.bytes.ByteArrayToString._
4+
import org.scalatest.matchers.must.Matchers
5+
import org.scalatest.wordspec.AnyWordSpec
6+
7+
class ByteArrayToStringTest extends AnyWordSpec with Matchers {
8+
"byte array" should {
9+
val helloInUtf8 = Array[Byte](104, 101, 108, 108, 111)
10+
val helloInUtf16Le = Array[Byte](104, 0, 101, 0, 108, 0, 108, 0, 111, 0)
11+
val hello = "hello"
12+
13+
"return correct String for usingNewString" in {
14+
usingNewString(helloInUtf8) mustBe hello
15+
}
16+
17+
"return correct String for usingToChar" in {
18+
usingToChar(helloInUtf8) mustBe hello
19+
}
20+
21+
"return correct String for usingDifferentCharSet" in {
22+
usingDifferentCharSet(helloInUtf16Le) mustBe hello
23+
}
24+
}
25+
}

0 commit comments

Comments
 (0)