我需要将ASCII字符转换为(7位)二进制。
我看过this,但是它给了我8位的二进制值,同时我希望它是7位的。例如:

C应该是1000011

CC应该是10000111000011

%应该是0100101

因此,我将代码更改为:

String s = "%";
byte[] bytes = s.getBytes();
StringBuilder binary = new StringBuilder();
for (int j = 0; j < 7; j++) {
    int val =  bytes[j];
    for (int i = 0; i < 8; i++) {
        binary.append((val & 128) == 0 ? 0 : 1);
        val <<= 1;
    }
    binary.append("");
}

System.out.println("'" + s + "' to binary: " + binary);


它抱怨:

java.lang.ArrayIndexOutOfBoundsException: 1


在行中:

int val =  bytes[j];


为了突出:

我用了

 for(int j=0;j<7;j++)
    int val =  bytes[j];


代替

for (byte b : bytes) int val = b;

最佳答案

您的代码中有2处更改,如下所示:

        String s = "%";
        byte[] bytes = s.getBytes();
        StringBuilder binary = new StringBuilder();
        for (int j = 0; j < bytes.length; j++) {
            int val = bytes[j];
            for (int i = 0; i < 7; i++) {
                val <<= 1;
                binary.append((val & 128) == 0 ? 0 : 1);
            }
        }

        System.out.println("'" + s + "' to binary: " + binary);

08-06 11:00