Domanda

in the following function, I have some trouble with an Array out of Bounds problem. It should convert a String of Digits into a BCD Format like this: "12345" -> 0x01 0x23 0x45 . The length of the String is not known.

public void StringtoBCD(String StringElement)
{
 ByteArrayOutputStream in = new ByteArrayOutputStream();
 if (!" ".equals(StringElement)){
     int i=0;
     byte[] tempBCD = StringElement.getBytes();
     for (i=0; i<tempBCD.length; i++){
       tempBCD[i]=(byte)(tempBCD[i]-0x30);
       }
      i=0;
      if (tempBCD.length %2 !=0){
      in.write(0);
      }
      while(i<tempBCD.length){
        in.write((tempBCD[i]<<4)+tempBCD[i+1]);
        i=i+2;
    }
   }
 }

I tried something like

while(i<tempBCD.length){
 in.write((tempBCD[i]<<4)+tempBCD[i+1]);
 if (i+3>(tempBCD.length)){
  i+= 1;
  }
   else {
    i+=2;
    }
}

without success. I am quite sure it's simple, but seems like I oversee something here. Any help is appreciated :)

È stato utile?

Soluzione

This works fine for me. Try it out ;) I just replaced the output stream for testing purposes, reorganized the code and added a "0" at the beginning of the String if it has an odd length.

    public void StringtoBCD(String StringElement) {
        PrintStream in = System.out;
        if(StringElement.length()%2 == 1) {
            StringElement= "0"+StringElement;
        }
        if (!" ".equals(StringElement)){
            byte[] tempBCD = StringElement.getBytes();
            for (int i=0; i<tempBCD.length; i++){
                tempBCD[i]=(byte)(tempBCD[i]-0x30);
            }
            for(int i = 0; i<tempBCD.length; i=i+2){
                in.write((tempBCD[i]<<4)+tempBCD[i+1]);
            }
        }
        in.flush();
    }

Btw. this does no work if StringElement contains A to F.

Altri suggerimenti

in.write((tempBCD[i]<<4)+tempBCD[i+1]); 

line leads the exception.

You are trying to access tempBCD[i+1] where i has the max value tempBCD.length()-1 and array index starts from 0.

You can do it like:

Create temp1BCD with a length 1 more than tempBCD, then do all the stuffs.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top