2 * Copyright (C) 1995-2005, Index Data ApS
3 * See the file LICENSE for details.
5 * $Id: ber_int.c,v 1.4 2005-01-16 21:51:50 adam Exp $
10 * \brief Implements BER INTEGER encoding and decoding.
12 * This source file implements BER encoding and decoding of
23 #include <sys/types.h>
29 #include <netinet/in.h>
34 static int ber_encinteger(ODR o, int val);
35 static int ber_decinteger(const unsigned char *buf, int *val, int max);
37 int ber_integer(ODR o, int *val)
44 if ((res = ber_decinteger(o->bp, val, odr_max(o))) <= 0)
46 odr_seterror(o, OPROTO, 50);
52 if ((res = ber_encinteger(o, *val)) < 0)
58 odr_seterror(o, OOTHER, 51); return 0;
63 * Returns: number of bytes written or -1 for error (out of bounds).
65 int ber_encinteger(ODR o, int val)
68 union { int i; unsigned char c[sizeof(int)]; } tmp;
70 tmp.i = htonl(val); /* ensure that that we're big-endian */
71 for (a = 0; a < (int) sizeof(int) - 1; a++) /* skip superfluous octets */
72 if (!((tmp.c[a] == 0 && !(tmp.c[a+1] & 0X80)) ||
73 (tmp.c[a] == 0XFF && (tmp.c[a+1] & 0X80))))
75 len = sizeof(int) - a;
76 if (ber_enclen(o, len, 1, 1) != 1)
78 if (odr_write(o, (unsigned char*) tmp.c + a, len) < 0)
81 fprintf(stderr, "[val=%d]", val);
87 * Returns: Number of bytes read or 0 if no match, -1 if error.
89 int ber_decinteger(const unsigned char *buf, int *val, int max)
91 const unsigned char *b = buf;
93 int res, len, remains;
94 union { int i; unsigned char c[sizeof(int)]; } tmp;
96 if ((res = ber_declen(b, &len, max)) < 0)
98 if (len+res > max || len < 0) /* out of bounds or indefinite encoding */
100 if (len > (int) sizeof(int)) /* let's be reasonable, here */
104 remains = sizeof(int) - len;
105 memcpy(tmp.c + remains, b, len);
110 memset(tmp.c, fill, remains);
115 fprintf(stderr, "[val=%d]", *val);