I want to parse a temperature from bytes.
The temperature consists of 2 bytes. The most significant bit of the first byte indicates if 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 have to make sure I ignore the most significant bit of the first byte. It's just a flag and not part of the temperature.
Ex: If I pass in 0xFFFF it returns -6553.5 but it should be -3276.7
How can I achieve this?
You can check whether 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 your 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;
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments