在java中将intel hex文件转换为二进制文件

时间:2015-12-12 16:57:47

标签: java binary embedded hex intel

我有一个java应用程序,它接收以前从嵌入式设备的二进制文件生成的intel hex文件。我需要使用intel hex文件重新创建原始二进制文件。显然,hex文件是使用标准的众所周知的程序生成的。根据我的理解,我基本上需要根据块偏移量和每行中每个32位十六进制的地址将字节放在正确的位置。我在这里阅读了intel hex的文档:intel hex。 以下是文件的外观:

:020000040000FA                             <-- block line for offset
:10000000A0DB0010B1020000297A0000C3FE00004E <-- data line
:10001000BD02000017FF00006FFF0000000000009D <-- data line
...............
more records from the first block
...............
:10FFE0002868283D07EB041000EB0806316891B142 <-- data line
:10FFF00042F63061084402684368304828212838B6 <-- data line
:020000040001F9                             <-- second block line offset
:1000000002F0B0FC3948009539A150F82420484648 <-- data line
:1000100033682CF057F8641C062CE3DB254898382D <-- data line
...............
and so on more blocks
...............
:1079E000321014DD1A0332061A990829741CF9188A <-- data line
:1079F00003C821146B1903320F1AC108297B1A25F9 <-- data line
:047A00002001380029                         <-- unused block
:04000005000000E512                         <-- unused block
:00000001FF                                 <-- end of file

我试图找到一个可以转换文件的jar或项目,但它们不会生成与原始文件相同的二进制文件,所以我写了一小段代码试图这样做:

    byte[] bytes = new byte[512 * 1024];//fixed standard size
    byte bDefault = (byte) 0xFF;//value to fill the gaps
    Arrays.fill(bytes, bDefault);//initialize the array with default values
    BufferedReader reader = null;
    int iOffset = 0;//block offset
    try {
        reader = new BufferedReader(new FileReader(new File(FILE)));
        String line;
        while ((line = reader.readLine()) != null) {
            if (!line.isEmpty()) {
                String strAddress = line.substring(3, 7);
                String strRecordType = line.substring(7, 9);
                String strData = line.substring(9, line.length() - 2);
                if (strRecordType.equals("04")) {//offset line
                    iOffset = Integer.parseInt(strData, 16) * 65536;//(16*4096=65536)
                } else if (strRecordType.equals("00")) {//data line
                    byte[] b = DatatypeConverter.parseHexBinary(strData);//get the bytes
                    for (int i = 0; i < b.length; i++) {//copy the bytes into the main byte array
                        bytes[iOffset + Integer.parseInt(strAddress, 16) + i] = b[i];
                    }
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
            }
        }
    }

但是这段代码不会产生与原始文件相同的字节。任何人都可以看到这段代码有什么问题吗? 编辑:我只想补充说每个块最多有4096行

0 个答案:

没有答案