0

在以下函数中,我遇到了 Array out of Bounds 问题。它应该将一串数字转换为 BCD 格式,如下所示: "12345" -> 0x01 0x23 0x45 。字符串的长度未知。

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;
    }
   }
 }

我尝试了类似的东西

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

没有成功。我很确定这很简单,但似乎我在这里监督了一些事情。任何帮助表示赞赏:)

4

2 回答 2

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

线导致异常。

您正在尝试访问 tempBCD[i+1] ,其中 i 具有最大值 tempBCD.length()-1 并且数组索引从 0 开始。

你可以这样做:

创建长度比 tempBCD 多 1 的 temp1BCD,然后执行所有操作。

于 2013-05-22T12:36:00.600 回答
1

这对我来说很好。试试看;)我只是出于测试目的替换了输出流,重新组织了代码并在字符串的开头添加了一个“0”,如果它的长度是奇数的话。

    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();
    }

顺便提一句。如果 StringElement 包含 A 到 F,这将不起作用。

于 2013-05-22T12:54:05.553 回答