2 * Copyright (c) 1995-2003, Index Data
3 * See the file LICENSE for details.
4 * Sebastian Hammer, Adam Dickmeiss
6 * $Id: ber_int.c,v 1.22 2003-03-11 11:03:31 adam Exp $
17 #include <sys/types.h>
18 #include <netinet/in.h>
23 static int ber_encinteger(ODR o, int val);
24 static int ber_decinteger(const unsigned char *buf, int *val, int max);
26 int ber_integer(ODR o, int *val)
33 if ((res = ber_decinteger(o->bp, val, odr_max(o))) <= 0)
35 odr_seterror(o, OPROTO, 50);
41 if ((res = ber_encinteger(o, *val)) < 0)
44 case ODR_PRINT: return 1;
45 default: odr_seterror(o, OOTHER, 51); return 0;
50 * Returns: number of bytes written or -1 for error (out of bounds).
52 int ber_encinteger(ODR o, int val)
55 union { int i; unsigned char c[sizeof(int)]; } tmp;
57 tmp.i = htonl(val); /* ensure that that we're big-endian */
58 for (a = 0; a < (int) sizeof(int) - 1; a++) /* skip superfluous octets */
59 if (!((tmp.c[a] == 0 && !(tmp.c[a+1] & 0X80)) ||
60 (tmp.c[a] == 0XFF && (tmp.c[a+1] & 0X80))))
62 len = sizeof(int) - a;
63 if (ber_enclen(o, len, 1, 1) != 1)
65 if (odr_write(o, (unsigned char*) tmp.c + a, len) < 0)
68 fprintf(stderr, "[val=%d]", val);
74 * Returns: Number of bytes read or 0 if no match, -1 if error.
76 int ber_decinteger(const unsigned char *buf, int *val, int max)
78 const unsigned char *b = buf;
80 int res, len, remains;
81 union { int i; unsigned char c[sizeof(int)]; } tmp;
83 if ((res = ber_declen(b, &len, max)) < 0)
85 if (len+res > max || len < 0) /* out of bounds or indefinite encoding */
87 if (len > (int) sizeof(int)) /* let's be reasonable, here */
91 remains = sizeof(int) - len;
92 memcpy(tmp.c + remains, b, len);
97 memset(tmp.c, fill, remains);
102 fprintf(stderr, "[val=%d]", *val);