【发布时间】:2019-05-07 18:40:38
【问题描述】:
我在互联网上引用了一个代码来将 comp 3 解压缩为 java 中的数字。我试图将示例 comp3 文件传递给代码,但没有得到正确的解包数据。我得到了一些奇怪的数字。我是这个概念的新手(comp 3),所以你们能帮我解决这个问题。提前致谢
下面是我的代码
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* Converts between integer and an array of bytes in IBM mainframe packed
* decimal format. The number of bytes required to store an integer is (digits +
* 1) / 2. For example, a 7 digit number can be stored in 4 bytes. Each pair of
* digits is packed into the two nibbles of one byte. The last nibble contains
* the sign, 0F for positive and 0C for negative. For example 7654321 becomes
* 0x76 0x54 0x32 0x1F.
*
* This class is immutable. Once constructed you can extract the value as an
* int, an array of bytes but you cannot change the value. Someone should
* implement equals() and hashcode() to make this thing truly useful.
*/
public class PackedDecimalToComp {
public static void main(String[] args) {
try {
// test.unpackData(" 0x12345s");
Path path = Paths.get("C:\\Users\\AV00499269\\Desktop\\Comp3 data file\\Comp3Test.txt");
byte[] data = Files.readAllBytes(path);
PackedDecimalToComp test = new PackedDecimalToComp();
test.unpackData(data);
} catch (Exception ex) {
System.out.println("Exception is :" + ex.getMessage());
}
}
private static String unpackData(byte[] packedData) {
String unpackedData = "";
final int negativeSign = 13;
for (int currentCharIndex = 0; currentCharIndex < packedData.length; currentCharIndex++) {
byte firstDigit = (byte) ((packedData[currentCharIndex] >>> 4) & 0x0F);
byte secondDigit = (byte) (packedData[currentCharIndex] & 0x0F);
unpackedData += String.valueOf(firstDigit);
if (currentCharIndex == (packedData.length - 1)) {
if (secondDigit == negativeSign) {
unpackedData = "-" + unpackedData;
}
} else {
unpackedData += String.valueOf(secondDigit);
}
}
System.out.println("Unpackeddata is :" + unpackedData);
return unpackedData;
}
}
我传递的 Comp3 文件有值 x019F
转换后,我得到解压后的数据为783031394
【问题讨论】:
-
unpackData方法看起来有效;你的问题在别处。检查 RecordEditor (sourceforge.net/projects/record-editor) 中的文件以确保正确 -
@BruceMartin 当我解压 comp 3 字段值 x019F 时,我应该将解压后的数据设为 19,对吗?由于我是 comp3 的新手,我有这个疑问,你能解释一下上面代码中使用的逻辑吗?我对此不太清楚
-
问题是你的文件中有 ascii string` x019F = x'7830313946' 十六进制。您需要将 binary 019F 放入文件中。最简单的方法就是用java程序写
-
请注意,压缩十进制负号代码可以是 X'B' (11) 或 X'D' (13)。这两个值都被接受为压缩十进制指令的输入。同样,X‘A‘、X‘C‘、X‘E‘和X‘F‘都表示值正号代码。
-
我在玩代码,它似乎可以按您的预期工作......您能举一个文件示例和一个无法正常工作的 hexdump 吗?
标签: java packed-decimal comp-3