【问题标题】:How to clear most significant bit in byte?如何清除字节中的最高有效位?
【发布时间】:2015-12-17 11:21:36
【问题描述】:

我想从字节解析温度。

温度由 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

我怎样才能做到这一点?

【问题讨论】:

  • 这个值与普通的大端序short有何不同?

标签: java byte bit


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    十六进制值 f 等价于二进制值 1111。0111 为 1+2+4=7 所以 0x7f 变为 01111111。

    return b &  0x7f;
    

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        【解决方案4】:

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

        如果 (num > 3276.8) num = num - 3276.8;

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-12-09
          • 1970-01-01
          • 2014-05-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多