我对9
(显示格式)和S9
(解压缩数字)类型感到困惑。我正在使用DB2存储过程读取Java
的文案输出。
* copy book
05 ABC PIC X(01).
05 XYZ PIC +9(09).
使用下面的Java代码,我能够正确地读取这些值。数字的符号也非常清楚,因为它要么是-
,要么是+
。
// java code
cobolResults.subString(1,1);
cobolResults.subString(2,9);
现在,将抄写簿更改为提供如下所示的未打包数字:
05 ABC PIC X(01).
05 XYZ PIC S9(09).
我不知道在Java中用正确的符号读取数字的正确逻辑是什么?
发布于 2015-08-12 23:01:08
首先,有一些来自IBM & 乐天星的包,用于从Cobol版权簿生成Java类。我自己的包JRecord也可以使用,但它是面向文件的,而不是在线处理。
基本上,字段的最后一个字符包含符号+数字。我猜数据来自大型机,所以对于US (CP037 / IBM237)来说,最后一个数字将是
0 1 2 3 4 5 6 7 8 9
positive { A B C D E F G H I
negative } J K L M N O P Q R
所以对于+123,它将是00000012C (C = +3),而-123将是00000012L。
更糟糕的是,+0和-0在不同的EBCIDIC方言和ASCII中也是不同的。因此,您要么需要确切地知道使用了哪个版本的Ebcidic,要么需要在字节级别上进行转换。
fromZoned方法在JRecord转换中执行转换:
private static int positiveDiff = 'A' - '1';
private static int negativeDiff = 'J' - '1';
private static char positive0EbcdicZoned = '{';
private static char negative0EbcdicZoned = '}';
public static String fromZoned(String numZoned) {
String ret;
String sign = "";
char lastChar, ucLastChar;
if (numZoned == null || ((ret = numZoned.trim()).length() == 0) || ret.equals("-")) {
return "";
}
lastChar = ret.charAt(ret.length() - 1);
ucLastChar = Character.toUpperCase(lastChar);
switch (ucLastChar) {
case 'A': case 'B': case 'C':
case 'D': case 'E': case 'F':
case 'G': case 'H': case 'I':
lastChar = (char) (ucLastChar - positiveDiff);
break;
case 'J': case 'K': case 'L':
case 'M': case 'N': case 'O':
case 'P': case 'Q': case 'R':
sign = "-";
lastChar = (char) (ucLastChar - negativeDiff);
break;
default:
if (lastChar == positive0EbcdicZoned) {
lastChar = '0';
} else if (lastChar == negative0EbcdicZoned) {
lastChar = '0';
sign = "-";
}
}
ret = sign + ret.substring(0, ret.length() - 1) + lastChar;
return ret;
}
但是,在字节级别上做起来更容易,应该如下所示(但没有测试代码):
private static final byte HIGH_NYBLE = (byte) 0xf0;
private static final byte LOW_NYBLE = (byte) 0x0f;
private static final byte ZONED_POSITIVE_NYBLE_OR = (byte) 0xCF;
private static final byte ZONED_NEGATIVE_NYBLE_OR = (byte) 0xDF;
private static final byte ZONED_NEGATIVE_NYBLE_VALUE = (byte) 0xD0;
signByte = bytes[bytes.length - 1];
negative = false;
if (((byte) (signByte & HIGH_NYBLE)) == ZONED_NEGATIVE_NYBLE_VALUE) {
negative = true;
}
long result = 0;
for (int i = 0; i < bytes.length; i++) {
result = result * 10 + (bytes[i] & LOW_NYBLE);
}
if (negative) {
result = -1 * result;
}
https://stackoverflow.com/questions/31970680
复制相似问题