merge 64-bit fixes from Fernando Lucas Rodriguez <fernando_lr@terra.es>
[debian/gcpegg] / xdsub.c
1 /*
2
3                            Hex dump utility
4
5                             by John Walker
6                WWW home page: http://www.fourmilab.ch/
7
8                 This program is in the public domain.
9
10 */
11
12 #ifdef HEXDUMP
13
14 #include <stdio.h>
15 #include <string.h>
16
17 #define EOS     '\0'
18
19 static char addrformat[80] = "%6X";
20 static char dataformat1[80] = "%02X";
21 static int bytesperline = 16, doublechar = 0,
22            dflen = 2;
23 static unsigned int fileaddr;
24 static unsigned char lineecho[32];
25
26 /*  OUTLINE  --  Edit a line of binary data into the selected output
27                  format.  */
28
29 static void outline(FILE *out, unsigned char *dat, int len)
30 {
31     char oline[132];
32     int i;
33
34     sprintf(oline, addrformat, fileaddr);
35     strcat(oline, ":");
36     for (i = 0; i < len; i++) {
37         char outedit[80];
38
39         sprintf(outedit, dataformat1, dat[i]);
40         strcat(oline, (i == (bytesperline / 2)) ? "  " : " ");
41         strcat(oline, outedit);
42     }
43
44     if (doublechar) {
45         char oc[2];
46         int shortfall = ((bytesperline - len) * (dflen + 1)) +
47                         (len <= (bytesperline / 2) ? 1 : 0);
48
49         while (shortfall-- > 0) {
50             strcat(oline, " ");
51         }
52         oc[1] = EOS;
53         strcat(oline, " | ");
54         for (i = 0; i < len; i++) {
55             int b = dat[i];
56
57             /* Map non-printing characters to "." according to the
58                definitions for ISO 8859/1 Latin-1. */
59
60             if (b < ' ' || (b > '~' && b < 145)
61                         || (b > 146 && b < 160)) {
62                 b = '.';
63             }
64             oc[0] = b;
65             strcat(oline, oc);
66         }
67     }
68     strcat(oline, "\n");
69     fputs(oline, out);
70 }
71
72 /*  XD  --  Dump a buffer.
73
74             xd(out, buf, bufl, dochar);
75
76             out     FILE * to which output is sent.
77             buf     Address of buffer to dump.
78             bufl    Buffer length in bytes.
79             dochar  If nonzero, show ASCII/ISO characters
80                     as well as hexadecimal.
81
82 */
83
84 void xd(FILE *out, void *bub, int bufl, int dochar)
85 {
86     int b, bp;
87     unsigned char *buf = (unsigned char *) bub;
88
89     bp = 0;
90     fileaddr = 0;
91     doublechar = dochar;
92
93     while (bufl-- > 0) {
94         b = *buf++;
95         if (bp >= bytesperline) {
96             outline(out, lineecho, bp);
97             bp = 0;
98             fileaddr += bytesperline;
99         }
100         lineecho[bp++] = b;
101     }
102
103     if (bp > 0) {
104         outline(out, lineecho, bp);
105     }
106 }
107 #endif