将字符串转换为Kotlin中的ByteArray [英] Typecast String to ByteArray in kotlin

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

问题描述

我在Kotlin中具有String格式的变量:

I have variable in String format in kotlin:

var a ="[B@53c1c428"

我想将其数据类型从String更改为 ByteArray ,即,将其数据类型转换为 ByteArray ,有点像:

I want to change it's datatype from String to ByteArray i.e typecast it to ByteArray, somewhat like:

var b: ByteArray = a

我也尝试过:

var b = a as ByteArray ,但这会引发异常

如果我这样做:

var b = a.toByteArray(),我得到如下输出:

[B@3aea9e4

但是我想要 [B @ 53c1c428 作为 ByteArray .

有什么建议吗?

推荐答案

仅需澄清一下: [B @ 53c1c428 "是该对象的十六进制哈希码,前缀为 B [@ .字符串"[B @ 53c1c428" 本身不包含重建 ByteArray 所需的数据.

Just to clarify: [B@53c1c428 is the hexadecimal hash code of that object with a B[@ prefix. The string "[B@53c1c428" itself does not contain the data needed to reconstruct the ByteArray.

考虑一下:

val str = "Test"
val byteArray = str.toByteArray()
println(Integer.toHexString(byteArray.hashCode())) // 1f32e575
println(byteArray) // [B@ + hash code as hexadecimal representation

val str2 = "This is a really long text and no 8 digit hex number in this world could encode it."
val byteArray2 = str2.toByteArray()
println(Integer.toHexString(byteArray2.hashCode())) // 279f2327
println(byteArray2) // [B@ + hash code as hexadecimal representation


toByteArray()已经为您提供了一个 ByteArray .如果要将单个数字打印为整数,请执行以下操作:


toByteArray() already gives you a ByteArray. If you want to print the single digits as integers do it like this:

val str = "Test"
println(str.toByteArray().joinToString(" "){ "$it" })

输出:

84 101115116

84 101 115 116

此输出足以完全恢复 ByteArray ,因为它包含所有必要的信息.

This output would be enough to fully restore the ByteArray, because it contains all necessary information.

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

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