How to clear the most significant bit in a byte?

I want to analyze temperature from bytes.

The temperature consists of 2 bytes. The most significant bit of the first byte indicates whether the temperature is positive or negative.

This is what I have so far:

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;
}

This works, but I still need to make sure that I ignore the most significant bit of the first byte. This is just a flag, not part of the temperature.

Example: If I pass in 0xFFFF, it will return -6553.5, but it should be -3276.7

How can i achieve this?

+4
source share
4 answers

You can check if the given temperature is minus using the following code.

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

You can use the following code to get the temperature value.

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;
}
+2

f 1111. 0111 1 + 2 + 4 = 7, 0x7f 01111111.

return b &  0x7f;
+1

You can reset the most significant bit with the mask 0x7f, then construct a 2-byte value using a binary shift and bitwise or.

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

Subtract the MSB value. If this bit is set, your number will be at least 32768. Therefore, subtract this amount.

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

0
source

Source: https://habr.com/ru/post/1620531/


All Articles