【问题标题】:How do I convert a byte array with null terminating character to a String in Kotlin?如何将具有空终止字符的字节数组转换为 Kotlin 中的字符串?
【发布时间】:2019-05-09 18:10:46
【问题描述】:

当我尝试通过蓝牙从设备中检索一个值时,它以 ASCII 形式出现,作为一个空终止的大端值。设备软件是用C编写的。我想检索十进制值,即0代替48、1代替49、9代替57等。

@Throws(IOException::class)
fun receiveData(socket: BluetoothSocket ? ): Int {
 val buffer = ByteArray(4)
 val input = ByteArrayInputStream(buffer)
 val inputStream = socket!!.inputStream
 inputStream.read(buffer)

 println("Value: " + input.read().toString()) // Value is 48 instead of 0, for example.

 return input.read()
}

我怎样才能检索到我想要的值?

【问题讨论】:

  • 这将肯定取决于用 C 编写的字符串的编码。
  • 会的,但我使用了一个蓝牙聊天应用程序来接收信号,它确实接收到所有 5 个整数。我的申请只收到 1 个。我想我需要知道它是如何编码的才能对其进行解码......

标签: string kotlin character-encoding null-terminated


【解决方案1】:

bufferedReader 很容易做到:

val buffer = ByteArray(4) { index -> (index + 48).toByte() }     // 1
val input = ByteArrayInputStream(buffer)

println(input.bufferedReader().use { it.readText() })            // 2
// println(input.bufferedReader().use(BufferedReader::readText)) // 3

Will output“0123”。

1。只需使用 init 函数对套接字的内容进行存根,该函数将buffer 的第一个元素设置为 48,第二个设置为 49,第三个设置为 50,第四个设置为 51。

2。默认字符集是 UTF-8,即"superset" of ASCII

3。这只是调用{ it.readText() } 的另一种风格。

【讨论】:

    【解决方案2】:

    我的函数最终采取了以下形式。这使我能够以十进制形式检索所有 5 位数字:

    @Throws(IOException::class)
    fun receiveData(socket: BluetoothSocket ? ): String {
     val buffer = ByteArray(5)
      (socket!!.inputStream).read(buffer)
     println("Value: " + String(buffer))
     return String(buffer)
    }
    

    对于我的特殊问题,输入变量是在将数据读入缓冲区之前创建的。由于对数据中的每个索引都调用了 read 方法,所以我只得到了第一个数字。

    查看Java方法public int read()的解释:

    Reads the next byte of data from this input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-15
      • 1970-01-01
      • 2012-12-23
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 2011-05-24
      • 1970-01-01
      相关资源
      最近更新 更多