我想从字节解析温度。
温度由 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,它会返回 -6553.5 但它应该是 -3276.7
我怎样才能做到这一点?
最佳答案
您可以使用以下代码检查给定温度是否为零。
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;
}
关于java - 如何清除字节中的最高有效位?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34333327/