xref: /XiangShan/tools/readmemh/groupby-4byte.c (revision c6d439803a044ea209139672b25e35fe8d7f4aa0)
1 /***************************************************************************************
2 * Copyright (c) 2020-2021 Institute of Computing Technology, Chinese Academy of Sciences
3 *
4 * XiangShan is licensed under Mulan PSL v2.
5 * You can use this software according to the terms and conditions of the Mulan PSL v2.
6 * You may obtain a copy of Mulan PSL v2 at:
7 *          http://license.coscl.org.cn/MulanPSL2
8 *
9 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
10 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
11 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
12 *
13 * See the Mulan PSL v2 for more details.
14 ***************************************************************************************/
15 
16 #include <stdio.h>
17 #include <assert.h>
18 #include <stdint.h>
19 
20 int main(int argc, char *argv[]) {
21   assert(argc == 3);
22 
23   FILE *in = fopen(argv[1], "rb");
24   assert(in != NULL);
25 
26   FILE *out = fopen(argv[2], "w");
27   assert(out != NULL);
28 
29   char line[128];
30   uint32_t addr;
31   union {
32     uint8_t _8[4];
33     uint32_t _32;
34   } data[4];
35   while (fgets(line, 128, in) != NULL) {
36     if (line[0] == '@') {
37       sscanf(line + 1, "%x", &addr);
38       assert(addr % 4 == 0);
39       fprintf(out, "@%08x\n", addr / 4);
40     }
41     else {
42       int ret = sscanf(line,
43           "%hhx%hhx%hhx%hhx"
44           "%hhx%hhx%hhx%hhx"
45           "%hhx%hhx%hhx%hhx"
46           "%hhx%hhx%hhx%hhx",
47           &data[0]._8[0], &data[0]._8[1], &data[0]._8[2], &data[0]._8[3],
48           &data[1]._8[0], &data[1]._8[1], &data[1]._8[2], &data[1]._8[3],
49           &data[2]._8[0], &data[2]._8[1], &data[2]._8[2], &data[2]._8[3],
50           &data[3]._8[0], &data[3]._8[1], &data[3]._8[2], &data[3]._8[3]);
51 
52       assert(ret == EOF || ret == 4 || ret == 8 || ret == 12 || ret == 16);
53 
54       if (ret == EOF) continue;
55 
56       if (ret >=  4) fprintf(out, "%08x ", data[0]._32);
57       if (ret >=  8) fprintf(out, "%08x ", data[1]._32);
58       if (ret >= 12) fprintf(out, "%08x ", data[2]._32);
59       if (ret >= 16) fprintf(out, "%08x ", data[3]._32);
60       fprintf(out, "\n");
61     }
62   }
63 
64   fclose(in);
65   fclose(out);
66 
67   return 0;
68 }
69