首页 > 解决方案 > 如何在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

标签: javaandroidbyte

解决方案


这可能是字节中的位顺序问题。请检查 Big Endian 与 Little Endian 模式。您得到的结果 114 (1110010) 与 39 (0100111) 正好相反,后者是位中的倒序。


推荐阅读