Putting all 8-bit binary sequences into a string array Java

Viewed 234

what I am trying to put all possible 256 binary bit sequences into a string array. In order to do that, I have created 8 for loops to have all the possible cases. Here's what I've tried so far.

static String[] BitSequences() {    
    int[] result = new int[256];
    for (int a = 0; a < 256; a++) {
        for (int i = 0; i < 2; i++){
            for (int j = 0; j < 2; j++){
                for (int k = 0; k < 2; k++){
                    for (int l = 0; l < 2; l++){
                        for (int m = 0; m < 2; m++){
                            for (int n = 0; n < 2; n++){
                                for (int o = 0; o < 2; o++){
                                    for (int p = 0; p < 2; p++){
                                        result[a] = ; //this part is a problem
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
    String str = Arrays.toString(result);
    System.out.println(str);
    return str;
}

This method is supposed to return a string array that contains all the possible cases. However, I don't know how to insert these value by making for-loops using int values. It is easy to print it out: ' System.out.println(i+j+k+.....+p) ' any help would be appreciated!

2 Answers

Consider using the built in conversion method for binary strings:

static String[] BitSequences() {    
    String[] result = new String[256];
    for (int a = 0; a < 256; a++) {
        result[a] = Integer.toBinaryString(a);
    }
    String str = Arrays.toString(result);
    System.out.println(str);
    return str;
}

An 8-bit, two's complement integer ranges from -128 to 127. To represent that range, we can use IntStream#rangeClosed.

From this answer, we can utilize BigInteger to left-pad the binary String (generated by Integer#toBinaryString) with 0s if its length is less than 8 (denoting that the value is positive).

Otherwise, the value represents a negative number, and its respective binary string will have a length greater than 8, which must be truncated to 8 characters using String#substring.

Finally, the Stream<String> can be collected to a String[] using Stream#toArray.

public static String[] generateBitSequences() { 
    return IntStream.rangeClosed(-128, 127)
        .mapToObj(Integer::toBinaryString)
        .map(BigInteger::new)
        .map(b -> String.format("%08d", b))    // Left pad positive values with 0s.
        .map(s -> s.substring(s.length() - 8)) // Remove leading 1s from negative values.
        .toArray(String[]::new);
}

Output:

[10000000, 10000001, ..., 01111110, 01111111]
Related