How Can I Convert A Bytearray Into An String And Reverse In Kotlin?
I'm trying to convert a String to a ByteArray, and convert the ByteArray to a String in Kotlin. My program was crashing, so I decided to debug a little, and my surprise was that wh
Solution 1:
When you print out a ByteArray
just using toString()
, you are effectively getting its object ID (it's a bit more complicated, but that definition will work for now), rather than the contents of the ByteArray
itself.
Solution 1
Pass a Charset as an argument to toString()
:
val bytes = "Hello!".toByteArray()
val string = bytes.toString(Charset.defaultCharset())
println(string) // Prints: "Hello!"
Solution 2
Pass the ByteArray
as an argument to the String
constructor:
val bytes = "Hello!".toByteArray()
val string = String(bytes)
println(string) // Prints: "Hello!"
Solution 2:
On each encoding the result changes so if you specify the encoding you would not lose any data, you can do that by using Charset
vals="this is an example"valb= s.toByteArray(Charset.defaultCharset())
println(b)
valss= String(b, Charset.defaultCharset())
println(ss)
Post a Comment for "How Can I Convert A Bytearray Into An String And Reverse In Kotlin?"