如何将具有空终止字符的字节数组转换为 Kotlin 中的字符串?

How do I convert a byte array with null terminating character to a String in Kotlin?

当我尝试通过蓝牙从设备中检索一个值时,它以 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()
}

如何检索我想要的值?

使用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() }.

的另一种方式

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

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

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

参见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.