【问题标题】:Kotlin Int to Byte ConversionKotlin Int 到字节的转换
【发布时间】:2021-09-14 18:21:00
【问题描述】:

Kotlin 1.5 将 16 位整数转换为长度为 2 的字节的命令是什么?第二个问题是 outputstream 在末尾需要一个字符串,因此它可以使用 toByteArray() 进行转换

# Original Python Code
...
i = int((2**16-1)*ratio) # 16 bit int
i.to_bytes(2, byteorder='big')
output = (i).to_bytes(2, byteorder='big') 


# Kotlin Code so far
var i = ((2.0.pow(16) - 1) * ratio).toInt() // Convert to 16 bit Integer
print("16 bit Int: " + i)
output = .....

....
...
val outputStream: OutputStream = socket.getOutputStream()
outputStream.write(output.toByteArray()) // write requires ByteArray for some reason

【问题讨论】:

    标签: arrays sockets kotlin binary outputstream


    【解决方案1】:

    这是简单的数学运算,因此最好手动计算并定义为扩展函数:

    fun Int.to2ByteArray() : ByteArray = byteArrayOf(toByte(), shr(8).toByte())
    

    然后就可以使用了:

    output = i.to2ByteArray()
    outputStream.write(output)
    

    注意,这个函数以小端序写入整数。如果您需要大端序,只需颠倒数组中项目的顺序即可。如果需要,您还可以添加一些最小/最大检查。

    另外,如果您只需要 16 位值,那么您可以考虑使用 ShortUShort 而不是 Int。它在内存使用方面没有太大变化,但它可能是一种更简洁的方法 - 我们可以将扩展命名为 toByArray(),并且我们不需要最小/最大检查。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-08
      • 1970-01-01
      • 2016-03-04
      • 2016-02-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多