帮助将Hex转换为布尔值?

帮助将Hex转换为布尔值?

问题描述:

我是Java新手。我正在学。帮助将Hex转换为布尔值?

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

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? 
    */ 
} 

我认为必须有更好的方法来执行此操作。这不是优雅的。此外,我坚持与二进制字符串值需要进行处理。

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

谢谢。我会试试看看它是否有效。 – 2010-06-19 16:45:58

+0

[true,false,true,false,true,false,true,false] 谢谢! – 2010-06-19 16:52:41

+0

我简化了循环。 – 2010-06-19 17:08:04