java - 如何在Java中将字节计算为16位
问题描述
我的值为 2 个字节。9C 80 其中第一个字节中的2位是下图的模式值,接下来的12位是步数。
这样,您总共有 2 个字节。
但我不知道如何以 16 位计算它。
使用 9C 80 字节提取 12 位的结果是 114。
这是错误的。正确答案是 39 步。39 步
9C 80的12bit能出来吗?
帮助。
下面是从c传过来的字节值的位位置。
struct ble_sync_sport_item
{
uint16_t mode : 2;
uint16_t sport_count : 12;
uint16_t active_time : 4;
uint16_t calories : 10;
uint16_t distance : 12;
};
这是我用来计算字节值的android代码。
private int bytesToInt(byte[] bytes , String value) {
int binaryToDecimal = 0;
int binaryToDecimal2 = 0;
int binaryToDecimal3 = 0;
int result = 0;
String s1 = "";
String s2 = "";
String s3 = "";
byteLog("5bytes ",bytes);
switch (value) {
case "ACT_STEP":
s1 = String.format("%8s", Integer.toBinaryString(bytes[0] & 0xFF)).replace(' ', '0');
s2 = String.format("%8s", Integer.toBinaryString(bytes[1] & 0xFF)).replace(' ', '0');
Log.d("FASDF ", "s1 == " + s1 + " s2 = " + s2 );
s1 = s1.substring(2, 8).concat(s2.substring(0,2));
s2 = s2.substring(2, 8).concat("00");
Log.d("FASDF ", "s1 == " + s1 + " s2 = " + s2 );
binaryToDecimal = Integer.parseInt(s1, 2);
binaryToDecimal2 = Integer.parseInt(s2, 2);
result = (int) ((int) binaryToDecimal) + ((int) binaryToDecimal2 << 8);
Log.d(tag,"result_step = " + result);
break;
这是我计算的结果的对数。39应该出来114出来。
结果二进制数10的模式值,我想得到100111二进制的sprot_count值。
D/FASDF: s1 == 10011100 = 0x9C,, s2 = 10000000 = 0x80 D/SevenHL5ConnectSync: result_step = 114
解决方案
这可能是字节中的位顺序问题。请检查 Big Endian 与 Little Endian 模式。您得到的结果 114 (1110010) 与 39 (0100111) 正好相反,后者是位中的倒序。
推荐阅读
- javascript - JQuery 拒绝执行内联脚本,因为它违反了 Chrome 扩展上的以下内容安全策略指令
- python - 如何从我的系统的所有目录中查找示例 *.mp3 文件?
- vba - VBA WORD循环遍历句子和句子行
- javascript - 如何访问选择标签中选定选项的对象?流星与火焰
- python-3.x - 计算特定暗区的平均宽度
- typescript - 使 TypeScript 将模块说明符转换为其解析的目标文件路径
- ios - 列表不异步更新列表中的行数?
- mysql - 表结构以支持单个列中的多次尝试
- html - 为什么数字不能正确粘贴在 HTML 输入字段中?
- c++ - n叉树中的多线程