Tupi
Tupi

Reputation: 258

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 when I convert a String into a ByteArray and I convert the same ByteArray to a String, the value isn't the same.

Like, if I do this:

val ivEnc = "[B@9a7d34b"
val dataEnc = "[B@1125ac5"

passTextEncrypted.setText(ivEnc.toByteArray().toString())
passTextDecrypted.setText(dataEnc.toByteArray().toString())

I expect to recive "[B@9a7d34b" and "[B@1125ac5". But every time I run the program, I recive different "random" values (all start with "[B@").

Is there something I'm doing wrong?

Upvotes: 3

Views: 7179

Answers (2)

Shay Kin
Shay Kin

Reputation: 2657

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

 val s = "this is an example"
 val b = s.toByteArray(Charset.defaultCharset())
 println(b)
 val ss = String(b, Charset.defaultCharset())
 println(ss)

Upvotes: 0

Todd
Todd

Reputation: 31700

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!"

Upvotes: 4

Related Questions