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

时间:2018-12-08 01:12:54

标签: string kotlin character-encoding null-terminated

当我尝试通过蓝牙从设备检索一个值时,它以ASCII形式出现,即以null结尾的big-endian值。设备软件使用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()
}

如何获取我想要的值?

2 个答案:

答案 0 :(得分:1)

使用bufferedReader很容易:

UserClass

Will output“ 0123”。

1 。只需使用初始化函数将套接字的内容存根即可,该函数将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 的第一个元素设置为48,第二个设置为49,第三个设置为50,第四个设置为51。

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

3 。这只是调用buffer的另一种方式。

答案 1 :(得分:1)

我的函数最终采用以下形式。这使我能够以十进制形式检索所有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.