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

Android项目:字节数组转unsigned short及电池待机时间计算问询

Android电池电流解析与待机时间计算

一、字节数组转无符号16位整数

针对接收的字节数组[-14, -5],由于Java/Kotlin无原生无符号short类型,可通过以下步骤转换:

步骤说明

  1. 确认字节序:BLE设备传输通常采用小端序(Little Endian),需匹配实际设备协议;
  2. 将字节数组包装为ByteBuffer,指定字节序后读取有符号short;
  3. 通过& 0xFFFF位运算,将有符号short转为无符号整数(范围0~65535)。

Kotlin代码示例

val currentBytes = byteArrayOf(-14, -5)
// 按小端序读取有符号short
val signedCurrent = ByteBuffer.wrap(currentBytes)
    .order(ByteOrder.LITTLE_ENDIAN)
    .short
// 转为无符号16位整数
val unsignedCurrent = signedCurrent.toInt() and 0xFFFF

Java代码示例

byte[] currentBytes = {-14, -5};
// 按小端序读取有符号short
short signedCurrent = ByteBuffer.wrap(currentBytes)
        .order(ByteOrder.LITTLE_ENDIAN)
        .getShort();
// 转为无符号16位整数
int unsignedCurrent = signedCurrent & 0xFFFF;

计算示例:[-14, -5]按小端序转换后,无符号值为64498(计算过程:(-14 & 0xFF) + ((-5 & 0xFF) << 8) = 242 + 251*256 = 64498)。

二、计算剩余待机时间

已知电池容量为12800 mAh,待机时间计算公式:

总小时数 = 电池容量(mAh) / 电流(mA)

将总小时数拆分为整数小时和小数部分转分钟(小数×60取整),最终按hours & minutes格式输出。

Kotlin代码示例

val batteryCapacity = 12800 // mAh
val totalHours = batteryCapacity.toDouble() / unsignedCurrent
val hours = totalHours.toInt()
val minutes = ((totalHours - hours) * 60).toInt()
// 格式化输出
val standbyTime = "$hours & $minutes"

Java代码示例

int batteryCapacity = 12800; // mAh
double totalHours = (double) batteryCapacity / unsignedCurrent;
int hours = (int) totalHours;
int minutes = (int) ((totalHours - hours) * 60);
// 格式化输出
String standbyTime = hours + " & " + minutes;

计算示例:当电流为64498 mA时,总小时数≈0.198,输出结果为0 & 12。

注意事项

  • 若设备采用大端序(Big Endian),需将ByteOrder.LITTLE_ENDIAN改为ByteOrder.BIG_ENDIAN;
  • 若设备用负号表示放电电流,可先取signedCurrent的绝对值再计算;
  • 实际开发中需加入异常处理(如电流为0时避免除以0)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 01:40:56