Java 十六进制字符串转换为EBCDIC返回数字格式异常
我试图转换由十六进制数据组成的字符串,如Java 十六进制字符串转换为EBCDIC返回数字格式异常,java,string,utf-8,hex,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.len
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");
}
我做错了什么?如何获得相应的EBCDIC值?十六进制是基数16,而不是基数10。改变
Byte valueOf = Byte.valueOf(s, 10);
到
或用于获取基本类型(而不是包装器)
简单一行:
public static String toEbcdic( String hexStr ) throws IOException {
return new String( DatatypeConverter.parseHexBinary( hexStr ), "CP1047" );
}
通过转换为字节数组并在CP1047中创建新字符串,代码的方向是正确的。 您只需解决两个问题即可使其正常工作:
解决方案很简单:解析为short并回溯到byte
import java.io.IOException;
import java.nio.ByteBuffer;
public class Q45235042 {
public static String toEbcdic( String strToConvert ) throws IOException {
String[] test = strToConvert.split( "(?<=\\G..)" );
ByteBuffer sb = ByteBuffer.allocate( test.length );
for ( String s : test )
sb.put( (byte) Short.parseShort( s, 16 ) );
return new String( sb.array(), "CP1047");
}
public static void main( String[] args ) throws IOException {
System.out.println( toEbcdic( "C120C2" ) );
}
}
import java.io.IOException;
导入java.nio.ByteBuffer;
公开课Q45235042{
公共静态字符串toEbcdic(字符串strToConvert)引发IOException{
String[]test=strotconvert.split(“(?我没有尝试将其转换为十六进制,而是ebcdic值。否。您尝试将十六进制值转换为二进制。和”c"不是十进制中的有效数字。好吧,那么我如何将十六进制字符串转换为ebcdic表示形式呢?经过一周的辛苦工作,你救了我。真希望这以前发生过。谢谢!我从未想过先短后字节。但一行代码太棒了。再次感谢!不幸的是,赏金可以在20小时后颁发,所以我将放弃o一旦时间过去,它就会消失。:)
byte valueOf = Byte.parseByte(s, 16);
public static String toEbcdic( String hexStr ) throws IOException {
return new String( DatatypeConverter.parseHexBinary( hexStr ), "CP1047" );
}
import java.io.IOException;
import java.nio.ByteBuffer;
public class Q45235042 {
public static String toEbcdic( String strToConvert ) throws IOException {
String[] test = strToConvert.split( "(?<=\\G..)" );
ByteBuffer sb = ByteBuffer.allocate( test.length );
for ( String s : test )
sb.put( (byte) Short.parseShort( s, 16 ) );
return new String( sb.array(), "CP1047");
}
public static void main( String[] args ) throws IOException {
System.out.println( toEbcdic( "C120C2" ) );
}
}