代码之家  ›  专栏  ›  技术社区  ›  Adam Outler

帮助将十六进制转换为布尔?

  •  2
  • Adam Outler  · 技术社区  · 15 年前

    我是爪哇人。我在学习。

    我正在尝试执行以下操作: 将十六进制字符串转换为二进制,然后将二进制处理为一系列布尔值。

        public static void getStatus() {
        /*
         * CHECKTOKEN is a 4 bit hexadecimal 
         * String Value in FF format. 
         * It needs to go into binary format 
         */
        //LINETOKEN.nextToken = 55 so CHECKTOKEN = 55
        CHECKTOKEN = LINETOKEN.nextToken();
        //convert to Integer  (lose any leading 0s)
        int binaryToken = Integer.parseInt(CHECKTOKEN,16);
        //convert to binary string so 55 becomes 85 becomes 1010101
        //should be 01010101
        String binaryValue = Integer.toBinaryString(binaryToken);
        //Calculate the number of required leading 0's
        int leading0s = 8 - binaryValue.length();
        //add leading 0s as needed
        while (leading0s != 0) {
            binaryValue = "0" + binaryValue;
            leading0s = leading0s - 1;
        }
        //so now I have a properly formatted hex to binary
        //binaryValue = 01010101
        System.out.println("Indicator" + binaryValue);
        /*
         * how to get the value of the least 
         * signigicant digit into a boolean 
         * variable... and the next?
         */
    }
    

    我认为必须有更好的方法来执行这个动作。这不优雅。另外,我还使用了一个需要以某种方式处理的二进制字符串值。

    1 回复  |  直到 14 年前
        1
  •  3
  •   Michael Barker    15 年前
    public static void main(String[] args) {
    
        String hexString = "55";
    
        int value = Integer.parseInt(hexString, 16);
    
        int numOfBits = 8;
    
        boolean[] booleans = new boolean[numOfBits];
    
        for (int i = 0; i < numOfBits; i++) {
            booleans[i] = (value & 1 << i) != 0;
        }
    
        System.out.println(Arrays.toString(booleans));
    }