繁体   English   中英

ByteArrayOutputStream的数字字符串

[英]String of Digits to ByteArrayOutputStream

在下面的函数中,我遇到了一个关于数据超出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;
    }
}

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

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

线引导例外。

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

你可以这样做:

创建比tempBCD长1的temp1BCD,然后做所有的东西。

这对我来说很好。 尝试一下;)我只是替换输出流用于测试目的,重新组织代码并在字符串的开头添加一个“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,这不起作用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM