如何将 ByteArray 转换为 String 并在 Kotlin 中反转? [英] How can I convert a ByteArray into an String and reverse in Kotlin?

查看:251
本文介绍了如何将 ByteArray 转换为 String 并在 Kotlin 中反转?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 String 转换为 ByteArray,并在 Kotlin 中将 ByteArray 转换为 String.

I'm trying to convert a String to a ByteArray, and convert the ByteArray to a String in Kotlin.

我的程序崩溃了,所以我决定调试一下,令我惊讶的是,当我将一个 String 转换为 ByteArray 并将相同的 ByteArray 转换为 String 时,值不一样.

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.

比如,如果我这样做:

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

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

我希望收到[B@9a7d34b"和[B@1125ac5".但是每次我运行程序时,我都会收到不同的随机"结果.值(均以[B@"开头).

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@").

我做错了什么吗?

推荐答案

当您仅使用 toString() 打印出 ByteArray 时,您实际上是在获取其对象 ID(它有点复杂,但该定义现在适用),而不是 ByteArray 本身的内容.

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.

解决方案 1

将字符集作为参数传递给 toString():

Pass a Charset as an argument to toString():

val bytes = "Hello!".toByteArray()
val string = bytes.toString(Charset.defaultCharset())

println(string) // Prints: "Hello!"

解决方案 2

ByteArray 作为参数传递给 String 构造函数:

Pass the ByteArray as an argument to the String constructor:

val bytes = "Hello!".toByteArray()
val string = String(bytes)

println(string) // Prints: "Hello!"

这篇关于如何将 ByteArray 转换为 String 并在 Kotlin 中反转?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆