Android 8 bit to 16 bit representation for Negative Numbers

风流意气都作罢 提交于 2020-01-23 13:52:34

问题


Refer to the question How to Convert two 8 bit represented byte to single 16 bit represented integer value in Android. I got an answer like this

short yourinteger16 = (short)(((bytes[0] & 0xFF) << 8) | (bytes[1] & 0xFF));

This answer is correct for the positive number. But in the case of the negative number, it's failing.

For example, I am sending the value from the BLE to the application as -10. The value will convert from the BLE as -10000 because of mAh/mV conversion of current and voltage. These values are split into two bytes and I am getting the byte value as -39 and -16 in my application. I am passing the byte to the method as like below.

short yourinteger16 = (short)(((-39 & 0xFF) << 8) | (-16 & 0xFF));

But I am getting the result as 9.77 as the float value of yourinteger16 .

Anyone has any idea about this?. Any solution please update me.

Full Code:

Integer ampValue = null;
        if (mBleDataHashMap.containsKey(SuperMuttBleConst.RESP_I_HIGH) &&
                mBleDataHashMap.containsKey(SuperMuttBleConst.RESP_I_LOW)) {
            ampValue = get8ByteTo16Byte(mBleDataHashMap.get(SuperMuttBleConst.RESP_I_HIGH),
                    mBleDataHashMap.get(SuperMuttBleConst.RESP_I_LOW));

        }
        if (ampValue != null) {
            float newAmp = ampValue.floatValue();
            newAmp = newAmp/1000;
            mAmpTextvw.setText("" + newAmp);
        }

Method

 protected Integer get8ByteTo16Byte(int firstValue, int secondValue) {
        Short integerValue =  (short)((((byte) firstValue & 0xFF) << 8) | ((byte) secondValue & 0xFF));
        return new Integer(integerValue);
    }

回答1:


You're receiving -39 and -16 perfectly (the high and low bytes for -10000, respectively).

Use addition instead of ORing the high and low bytes. Please try the following

    short result = (short) (((short)(-39 & (byte)0xFF) << 8) + (short)(-16 & (byte)0xFF));

The negative low bytes is causing trouble for the high byte when dealing with 2's complement arithmetic.



来源:https://stackoverflow.com/questions/38118276/android-8-bit-to-16-bit-representation-for-negative-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!