Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to convert an integer to a 7 bit Boolean binary array. So far the code doesn't work: If i input say integer 8 to be converted, instead of 0001000 I get 1000000, or say 15 I should get 0001111 but I get 1111000. The char array is a different length to the binary array and the positions are wrong.

public static void main(String[] args){

    String maxAmpStr = Integer.toBinaryString(8);
    char[] arr = maxAmpStr.toCharArray();
    boolean[] binaryarray = new boolean[7];
    for (int i=0; i<maxAmpStr.length(); i++){
        if (arr[i] == '1'){             
            binaryarray[i] = true;  
        }
        else if (arr[i] == '0'){
            binaryarray[i] = false; 
        }
    }

    System.out.println(maxAmpStr);
    System.out.println(binaryarray[0]);
    System.out.println(binaryarray[1]);
    System.out.println(binaryarray[2]);
    System.out.println(binaryarray[3]);
    System.out.println(binaryarray[4]);
    System.out.println(binaryarray[5]);
    System.out.println(binaryarray[6]);
}

Any help is appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
138 views
Welcome To Ask or Share your Answers For Others

1 Answer

There's really no need to deal with strings for this, just do bitwise comparisons for the 7 bits you're interested in.

public static void main(String[] args) {

    int input = 15;

    boolean[] bits = new boolean[7];
    for (int i = 6; i >= 0; i--) {
        bits[i] = (input & (1 << i)) != 0;
    }

    System.out.println(input + " = " + Arrays.toString(bits));
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...