]> diplodocus.org Git - nmh/blob - sbr/snprintb.c
mhlsbr.c: Don't strchr(3) non-string NUL-less buffer.
[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
10
11 char *
12 snprintb (char *buffer, size_t n, unsigned v, char *bits)
13 {
14 size_t len;
15 int i, j;
16 char c, *bp;
17
18 snprintf (buffer, n, bits && *bits == 010 ? "0%o" : "0x%x", v);
19 len = strlen(buffer);
20 bp = buffer + len;
21 n -= len;
22
23 if (bits && *++bits) {
24 j = 0;
25 *bp++ = '<';
26 while ((i = *bits++) && n > 1)
27 if (v & (1 << (i - 1))) {
28 if (j++ && n > 1) {
29 *bp++ = ',';
30 n--;
31 }
32 for (; (c = *bits) > 32 && n > 1; bits++) {
33 *bp++ = c;
34 n--;
35 }
36 }
37 else
38 for (; *bits > 32; bits++)
39 continue;
40 if (n > 1)
41 *bp++ = '>';
42
43 *bp = 0;
44 }
45
46 return buffer;
47 }