You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin/JVM中Python的bytes、BytesIO、struct模块对应实现咨询

Kotlin/JVM 对应 Python 字节操作组件实现

1. bytes → UByteArray

你已经知道:Python的bytes在Kotlin/JVM中对应UByteArray,它是无符号字节数组,和Python bytes语义完全匹配。

2. BytesIO → ByteArrayInputStream/ByteArrayOutputStream

Python的BytesIO是内存中的可读写字节流,Kotlin/JVM用两个标准库类实现对应功能:

  • 读取操作:使用ByteArrayInputStream,将UByteArray通过toByteArray()转为JVM标准的有符号ByteArray后传入,支持read()、read(byteArray)等读取方法。
  • 写入操作:使用ByteArrayOutputStream,支持write(byte)、write(byteArray)等写入方法,完成写入后可通过toByteArray()获取最终字节数组;结合ByteArrayInputStream就能实现读写切换,和BytesIO的用法一致。

示例代码:

// 模拟BytesIO的读写流程
val outputStream = ByteArrayOutputStream()
outputStream.write(0x41.toByte()) // 写入字节'A'
outputStream.write(byteArrayOf(0x42, 0x43)) // 写入字节数组

// 切换到读取模式
val inputStream = ByteArrayInputStream(outputStream.toByteArray())
val buffer = ByteArray(3)
inputStream.read(buffer)
println(buffer.decodeToString()) // 输出 "ABC"

3. struct模块 → java.nio.ByteBuffer

Python的struct模块负责字节与int、float等基本类型的转换,Kotlin/JVM中用java.nio.ByteBuffer实现,它支持指定字节序(大端/小端),覆盖struct的核心功能:

基本类型转字节

// 写入int、float,指定小端序(对应struct的"<"格式符)
val buffer = ByteBuffer.allocate(8)
buffer.order(ByteOrder.LITTLE_ENDIAN)
buffer.putInt(12345)
buffer.putFloat(3.14f)
val byteArray = buffer.array() // 获取转换后的字节数组

字节转基本类型

// 从字节数组读取int、float,同样指定小端序
val buffer = ByteBuffer.wrap(byteArray)
buffer.order(ByteOrder.LITTLE_ENDIAN)
val intValue = buffer.int // 读取int值
val floatValue = buffer.float // 读取float值

如果需要处理更复杂的格式(对应struct的复合格式化字符串),可以基于ByteBuffer封装自定义工具方法,满足特定解析需求。

内容的提问来源于stack exchange,提问作者ArekBulski

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 19:16:03