]> diplodocus.org Git - nmh/blob - sbr/snprintb.c
Improve fmttest output
[nmh] / sbr / snprintb.c
1 /* snprintb.c -- snprintf a %b string
2 *
3 * This code is Copyright (c) 2002, by the authors of nmh. See the
4 * COPYRIGHT file in the root directory of the nmh distribution for
5 * complete copyright information.
6 */
7
8 #include "h/mh.h"
9 #include "snprintb.h"
10
11
12 char *
13 snprintb (char *buffer, size_t n, unsigned v, char *bits)
14 {
15 size_t len;
16 int i, j;
17 char c, *bp;
18
19 snprintf (buffer, n, bits && *bits == 010 ? "0%o" : "0x%x", v);
20 len = strlen(buffer);
21 bp = buffer + len;
22 n -= len;
23
24 if (bits && *++bits) {
25 j = 0;
26 *bp++ = '<';
27 while ((i = *bits++) && n > 1)
28 if (v & (1 << (i - 1))) {
29 if (j++ && n > 1) {
30 *bp++ = ',';
31 n--;
32 }
33 for (; (c = *bits) > 32 && n > 1; bits++) {
34 *bp++ = c;
35 n--;
36 }
37 }
38 else
39 for (; *bits > 32; bits++)
40 continue;
41 if (n > 1)
42 *bp++ = '>';
43
44 *bp = 0;
45 }
46
47 return buffer;
48 }