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

Android BLE体重秤:Kotlin中字节数组转十进制体重值求助

如何将BLE体重秤返回的字节数组转换为体重值(Kotlin实现)

已知BLE体重秤返回的字节数组中,体重数据对应索引5和6的两个字节(从0开始计数),通过分析测试案例可推导出转换逻辑:

测试案例验证

字节数组(仅展示索引5、6)对应体重值计算过程
[0, 32]32gm0×256 + 32 = 32
[1, 108]364gm1×256 + 108 = 364
[0, -17]239gm0×256 + (256-17) = 239
[2, 91]603gm2×256 + 91 = 603
[4, 16]1040gm4×256 + 16 = 1040

转换逻辑

由于Kotlin中Byte是有符号类型(范围-128~127),需要先将其转换为无符号整数:

  1. 取索引5的字节作为高字节,转无符号值:highByte.toUInt() and 0xFFU
  2. 取索引6的字节作为低字节,转无符号值:lowByte.toUInt() and 0xFFU
  3. 计算体重值:(高字节无符号值 shl 8) + 低字节无符号值,结果即为克数。

Kotlin实现代码

fun convertBytesToWeight(byteArray: ByteArray): UInt {
    require(byteArray.size >= 7) { "字节数组长度不足,无法提取体重数据" }
    val highByte = byteArray[5]
    val lowByte = byteArray[6]
    val highValue = highByte.toUInt() and 0xFFU
    val lowValue = lowByte.toUInt() and 0xFFU
    return (highValue shl 8) + lowValue
}

// 测试示例
fun main() {
    val testCases = listOf(
        byteArrayOf(-6, 5, 0, 3, 0, 0, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) to 32U,
        byteArrayOf(-6, 5, 0, 3, 0, 1, 108, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) to 364U,
        byteArrayOf(-6, 5, 0, 3, 0, 0, -17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) to 239U,
    )
    testCases.forEach { (bytes, expected) ->
        val result = convertBytesToWeight(bytes)
        println("计算结果: $result gm,预期值: $expected gm,匹配: ${result == expected}")
    }
}

说明

  • 函数返回UInt类型,确保无符号范围覆盖常规体重秤的最大测量值(最大支持65535gm,即65.5kg)
  • 加入数组长度校验,避免越界异常
  • 测试示例可直接运行验证结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 15:42:49