gpt4 book ai didi

java - 需要帮助将 EBCDIC 转换为十六进制

转载 作者:行者123 更新时间:2023-11-30 05:35:58 32 4
gpt4 key购买 nike

我正在编写一个 Hive UDF 将 EBCDIC 字符转换为十六进制。Hive 表中存在 Ebcdic 字符。目前我可以对其进行转换,但转换时会忽略一些字符。

示例:

这是存储在表中的 EBCDIC 值:

AGNSAñA¦ûÃÃÂõÂjÂq  à ()

转换后的十六进制:

c1c7d5e2000a5cd4f6ef99187d07067203a0200258dd9736009f000000800017112400000000001000084008403c000000000000000080

我想要的输出:

c1c7d5e200010a5cd4f6ef99187d0706720103a0200258dd9736009f000000800017112400000000001000084008403c000000000000000080

忽略转换以下 EBCDIC 字符:

01 - It is start of heading
10 - It is a escape
15 - New line.

下面是我迄今为止尝试过的代码:

public class EbcdicToHex extends UDF {
public String evaluate(String edata) throws UnsupportedEncodingException {
byte[] ebcdiResult = getEBCDICRawData(edata);
String hexResult = getHexData(ebcdiResult);
return hexResult;
}

public byte[] getEBCDICRawData (String edata) throws UnsupportedEncodingException {
byte[] result = null;

String ebcdic_encoding = "IBM-037";
result = edata.getBytes(ebcdic_encoding);

return result;
}

public String getHexData(byte[] result){
String output = asHex(result);
return output;
}

public static String asHex(byte[] buf) {
char[] HEX_CHARS = "0123456789abcdef".toCharArray();
char[] chars = new char[2 * buf.length];
for (int i = 0; i < buf.length; ++i) {
chars[2 * i] = HEX_CHARS[(buf[i] & 0xF0) >>> 4];
chars[2 * i + 1] = HEX_CHARS[buf[i] & 0x0F];
}
return new String(chars);
}
}

转换时,它会忽略一些 EBCDIC 字符。如何使它们也转换为十六进制?

最佳答案

我认为问题出在其他地方,我创建了一个小测试用例,在其中根据您声称被忽略的 3 个字节创建了一个字符串,但在我的输出中它们似乎确实被正确转换:

  private void run(String[] args) throws Exception {
byte[] bytes = new byte[] {0x01, 0x10, 0x15};
String str = new String(bytes, "IBM-037");

byte[] result = getEBCDICRawData(str);

for(byte b : result) {
System.out.print(Integer.toString(( b & 0xff ) + 0x100, 16).substring(1) + " ");
}

System.out.println();
System.out.println(evaluate(str));
}

输出:

01 10 15
011015

基于此,您的 getEBCDICRawDataevaluate 方法似乎都工作正常,让我相信您的 String 值一开始可能已经不正确。难道字符串已经缺少这些字符了吗?或者也许是一个远景,但也许字符集不正确?有不同的 EBCDIC 字符集,因此字符串可能是使用不同的字符集组成的?尽管我怀疑这会对 01、10 和 15 字节产生很大影响。

作为最后一句话,但可能与您的问题无关,我通常更喜欢在字符集对象上使用编码/解码函数来执行此类转换:

String charset = "IBM-037";
Charset cs = Charset.forName(charset);
ByteBuffer bb = cs.encode(str);
CharBuffer cb = cs.decode(bb);

关于java - 需要帮助将 EBCDIC 转换为十六进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56626455/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com