1

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?

Tupi
  • 218
  • 5
  • 13

2 Answers2

2

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!"
Todd
  • 30,472
  • 11
  • 81
  • 89
  • Ok, that works for now. And for converting a string to a byteArray, I can simply use `"Hello!".toByteArray()`? – Tupi Mar 13 '21 at 16:55
  • Yes, that works in this case as `toByteArray()` without arguments assumes you want the default Charset (which I think is UTF-8). If you wanted a _different_ charset, you'd have to specify it in both places: `"Hello".toByteArray(SomeCharSet)` and `bytes.toString(SomeCharSet)`. But using the default is safe and sensible. – Todd Mar 13 '21 at 16:57
0

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)
Shay Kin
  • 2,539
  • 3
  • 15
  • 22