scc

simple c99 compiler
git clone git://git.simple-cc.org/scc
Log | Files | Refs | README | LICENSE

bpack.c (1026B)


      1 #include <ctype.h>
      2 #include <stdarg.h>
      3 
      4 #include <scc/scc.h>
      5 
      6 int
      7 bpack(unsigned char *dst, char *fmt, ...)
      8 {
      9 	unsigned char *bp, *cp;
     10 	unsigned s;
     11 	unsigned long l;
     12 	unsigned long long q;
     13 	size_t n;
     14 	int d;
     15 	va_list va;
     16 
     17 	bp = dst;
     18 	va_start(va, fmt);
     19 	while (*fmt) {
     20 		switch (*fmt++) {
     21 		case '\'':
     22 			for (n = 0; isdigit(*fmt); n += d) {
     23 				n *= 10;
     24 				d = *fmt++ - '0';
     25 			}
     26 			cp = va_arg(va, unsigned char *);
     27 			while (n--)
     28 				*bp++ = *cp++;
     29 			break;
     30 		case 'c':
     31 			*bp++ = va_arg(va, unsigned);
     32 			break;
     33 		case 's':
     34 			s = va_arg(va, unsigned);
     35 			*bp++ = s >> 8;
     36 			*bp++ = s;
     37 			break;
     38 		case 'l':
     39 			l = va_arg(va, unsigned long);
     40 			*bp++ = l >> 24;
     41 			*bp++ = l >> 16;
     42 			*bp++ = l >> 8;
     43 			*bp++ = l;
     44 			break;
     45 		case 'q':
     46 			q = va_arg(va, unsigned long long);
     47 			*bp++ = q >> 56;
     48 			*bp++ = q >> 48;
     49 			*bp++ = q >> 40;
     50 			*bp++ = q >> 32;
     51 			*bp++ = q >> 24;
     52 			*bp++ = q >> 16;
     53 			*bp++ = q >> 8;
     54 			*bp++ = q;
     55 			break;
     56 		default:
     57 			va_end(va);
     58 			return -1;
     59 		}
     60 	}
     61 	va_end(va);
     62 
     63 	return bp - dst;
     64 }