java - 帮忙将十六进制转换为 boolean 值?

标签 java binary

我是 Java 新手。我在学习。

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

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

关于java - 帮忙将十六进制转换为 boolean 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3076228/

相关文章:

java - 执行更新查询时MySQL语法错误异常

java - 如何使用 Spring Boot 和 WildFly 11.0 配置 JNDI 数据源

c - 二进制形式的文件

c# - 根据 bool 值更改标志

java - 在不知道 JSON 结构的情况下在 Java 中解析嵌套的 JSON?

java - jlayer.javazoom播放器无法停止mp3

arduino - BCD转十进制和十进制转BCD

计算机中的二进制到十进制

java - 错误 : "attribute value must be constant". 我可以在编译时从枚举构造常量吗?

algorithm - 非还原除法算法