将HEX字符串转换为EBCDIC会返回数字格式异常

时间:2017-07-21 10:14:50

标签: java string utf-8 hex

我正在尝试转换由十六进制数据组成的字符串,例如C120,分别表示A(空格)。我正在获取字符串并尝试将其拆分为字符串数组。然后我尝试迭代此数组并获取相应的UTF-8值。以下是我的代码:

public static String toEbcdic(String strToConvert){
    String[] test = strToConvert.split("(?<=\\G..)");
    ByteBuffer sb = ByteBuffer.allocate(test.length);
    for (String s : test) {
        Byte valueOf = Byte.valueOf(s, 10);
        sb.put(valueOf);
    }
    return new String(sb.array(), "CP1047");
}

当传递输入C120C2时,我得到以下异常:

Exception in thread "main" java.lang.NumberFormatException: For input string: "C1"

我做错了什么?如何获得相应的EBCDIC值?

2 个答案:

答案 0 :(得分:1)

十六进制是基数16而不是基数10.更改

So the solution in my view can be:

1.You know in which location the file gets downloaded.So you can hard code the location of file in your script.If the name of excel is same everytime it is downloaded then it is good,otherwise you need to capture the name of file and store it.
2.You can continue on running your tests after downloading the file.
3.Now you can take the screen shot of the downloaded file once you are finished traversing all the pages.

Hope this helps.

Byte valueOf = Byte.valueOf(s, 10); 

使用Byte.parseByte(String, int)获取基本类型(而不是包装器)。

Byte valueOf = Byte.valueOf(s, 16);

答案 1 :(得分:1)

简单的单行:

ERROR TypeError: Cannot read property 'templateRef' of undefined

ERROR CONTEXT DebugContext_ {view: Object, nodeIndex: 3, nodeDef: Object, elDef: Object, elView: Object}

Unhandled Promise rejection: Cannot read property 'templateRef' of undefined ; Zone: <root> ; Task: Promise.then ; Value: TypeError: Cannot read property 'templateRef' of undefined

Error: Uncaught (in promise): TypeError: Cannot read property 'templateRef' of undefined

您的代码是正确的方向,通过转换为字节数组并在CP1047中创建一个新的字符串。 您只需修复两个问题即可使其正常工作:

  1. 字节串是十六进制(基数为16)而不是十进制(基数为10)。
  2. Java字节已签名,因此将其输入C1将触发超出范围的&#34;值&#34;例外。
    解决方案很简单:解析为short并转回byte。
  3. 这是一个完整的固定示例:

    public static String toEbcdic( String hexStr ) throws IOException {
       return new String( DatatypeConverter.parseHexBinary( hexStr ), "CP1047" );
    }