【问题标题】:How to check if bit is set in Hex-String?如何检查是否在十六进制字符串中设置了位?
【发布时间】:2012-04-25 14:10:33
【问题描述】:

变速杆...

我必须做点事情,这让我心烦意乱。

我得到一个十六进制值作为字符串(例如:“AFFE”)并且必须决定是否设置了字节一的第 5 位。

public boolean isBitSet(String hexValue) {
    //enter your code here
    return "no idea".equals("no idea")
}

有什么提示吗?

问候,

博斯科普

【问题讨论】:

    标签: java hex bit-manipulation


    【解决方案1】:

    最简单的方法是将String转换为int,并使用位运算:

    public boolean isBitSet(String hexValue, int bitNumber) {
        int val = Integer.valueOf(hexValue, 16);
        return (val & (1 << bitNumber)) != 0;
    }               ^     ^--- int value with only the target bit set to one
                    |--------- bit-wise "AND"
    

    【讨论】:

      【解决方案2】:

      假设字节一用最后两位数字表示,字符串大小固定为4个字符,那么答案可能是:

      return (int)hexValue[2] & 1 == 1;
      

      如您所见,您不需要将整个字符串转换为二进制来评估第 5 位,它确实是第 3 个字符的 LSB。

      现在,如果十六进制字符串的大小是可变的,那么您将需要类似:

      return (int)hexValue[hexValue.Length-2] & 1 == 1;
      

      但由于字符串的长度可以小于 2,所以会更安全:

      return hexValue.Length < 2 ? 0 : (int)hexValue[hexValue.Length-2] & 1 == 1;
      

      正确答案可能会有所不同,具体取决于您认为是字节 1 和位 5。

      【讨论】:

        【解决方案3】:

        这个怎么样?

         int x = Integer.parseInt(hexValue);
         String binaryValue = Integer.toBinaryString(x);
        

        然后您可以检查字符串以检查您关心的特定位。

        【讨论】:

          【解决方案4】:

          使用 BigInteger 和它的 testBit 内置函数

          static public boolean getBit(String hex, int bit) {
              BigInteger bigInteger = new BigInteger(hex, 16);
              return bigInteger.testBit(bit);
          }
          

          【讨论】:

            猜你喜欢
            • 2012-07-20
            • 2012-02-22
            • 1970-01-01
            • 2014-03-10
            • 1970-01-01
            • 1970-01-01
            • 2014-11-14
            • 2014-03-26
            • 2011-12-23
            相关资源
            最近更新 更多