如何清除字节中的最高有效位?

How to clear most significant bit in byte?

我想从字节解析温度。

温度由2个字节组成。第一个字节的最高有效位指示温度是正值还是负值。

这是我目前拥有的:

public double parseTemperatureBytes(byte[] temperatureBytes) {
    // Must be divided by 10 (1 decimal)
    // First bit indicates sign (bit 1 = negative, bit 0 = positive)
    // Range [0x7FFF] : [-3276.7 … +3276.7]

    byte firstByte = temperatureBytes[0];
    int positiveOrNegative = ParseUtils.getMostSignificantBit(firstByte);
    boolean isPositive = positiveOrNegative == 0;

    String temperatureHex = ParseUtils.bytesToHex(temperatureBytes);
    int temperatureHexToInteger = Integer.parseInt(temperatureHex, 16);
    double temperature = temperatureHexToInteger / (double) 10;

    if (!isPositive) {
        temperature = -temperature;
    }

    return temperature;
}


// ParseUtils

public static int getMostSignificantBit(byte b) {
    return (b & 0xff) >> 7;
}

这可行,但我仍然必须确保忽略第一个字节的最高有效位。它只是一个标志,而不是温度的一部分。

例如: 如果我传入 0xFFFF 它 returns -6553.5 但它应该是 -3276.7

我怎样才能做到这一点?

十六进制值f相当于二进制值1111。0111是1+2+4=7所以0x7f变成01111111。

return b &  0x7f;

减去 MSB 的大小。如果设置了该位,您的数字将至少为 32768。因此减去该数量。

if (num > 3276.8) num = num - 3276.8;

您可以使用 0x7f 掩码重置最高有效位,然后使用二进制移位和按位或构造 2 字节值。

int high = temperatureBytes[0] & 0x7f;
int low = temperatureBytes[1];
int value = (high << 8) | low;
double temperature = value / 10.0;

您可以使用以下代码检查给定温度是否为负值..

public static int getMostSignificantBit(byte b) {
    return b & 0x80;
}

您可以使用以下代码获取您的温度值..

public static double parseTemperatureBytes(byte[] temperatureBytes) {
    int firstByte = temperatureBytes[0] & 0x7F;
    int secondByte = temperatureBytes[1] & 0xFF;
    double temperature = ((firstByte << 8) | secondByte) / 10.0;

    if (getMostSignificantBit(temperatureBytes[0]) > 0) {
        temperature = -temperature;
    }

    return temperature;
}