-5

What is the problem in this code?

public String convertBinaryStringToString(String string){
    StringBuilder sb = new StringBuilder();
    char[] chars = string.toCharArray();

    // String TextKey="";
    String plaintext="";

    //for each character
    for (int j = 0; j < chars.length; j+=8) {
        int idx = 0;
        int sum =0;

        //for each bit in reverse
        for (int i = 7; i>= 0; i--) {
            if (chars[i+j] == '1') {
                sum += 1 << idx;
            }
            idx++;
        }
        System.out.println("The ascii for the binary is :"+sum); //debug
        plaintext = (char)sum+"";
        plainstr += plaintext;
        key_arr = StrKey.toCharArray();
        System.out.println("The ascii for chracter for ascii is :"+plainstr); 
    }
    return plainstr;
}

It gives to me this runtime error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7 
at dec.convertBinaryStringToString(dec.java:83) 
at dbconnection.updateRows(dbconnection.java:122) 
at mainenc.main(mainenc.java:8) 

line 83 is if (chars[i+j] == '1')

dur
  • 13,039
  • 20
  • 66
  • 96

1 Answers1

0

Note that you go over 8-byte chunks, and for each chunk you try to go over each character in the chunk. The problem occurs when you process the very last chunk, as it can have less than 8 characters. Rewrite this line:

if (chars[i+j] == '1') {

into

if (i + j < chars.length && chars[i+j] == '1') {
Ishamael
  • 11,336
  • 4
  • 28
  • 46