帮助将Hex转换为布尔值?

时间:2010-06-19 16:21:21

标签: java binary

我是Java新手。我在学习。

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

    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 个答案:

答案 0 :(得分:3)

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