2 * Copyright (c) 1995-2004, Index Data
3 * See the file LICENSE for details.
5 * $Id: ber_int.c,v 1.2 2004-10-15 00:18:59 adam Exp $
10 * \brief Implements BER INTEGER encoding and decoding.
12 * This source file implements BER encoding and decoding of
25 #include <sys/types.h>
26 #include <netinet/in.h>
31 static int ber_encinteger(ODR o, int val);
32 static int ber_decinteger(const unsigned char *buf, int *val, int max);
34 int ber_integer(ODR o, int *val)
41 if ((res = ber_decinteger(o->bp, val, odr_max(o))) <= 0)
43 odr_seterror(o, OPROTO, 50);
49 if ((res = ber_encinteger(o, *val)) < 0)
52 case ODR_PRINT: return 1;
53 default: odr_seterror(o, OOTHER, 51); return 0;
58 * Returns: number of bytes written or -1 for error (out of bounds).
60 int ber_encinteger(ODR o, int val)
63 union { int i; unsigned char c[sizeof(int)]; } tmp;
65 tmp.i = htonl(val); /* ensure that that we're big-endian */
66 for (a = 0; a < (int) sizeof(int) - 1; a++) /* skip superfluous octets */
67 if (!((tmp.c[a] == 0 && !(tmp.c[a+1] & 0X80)) ||
68 (tmp.c[a] == 0XFF && (tmp.c[a+1] & 0X80))))
70 len = sizeof(int) - a;
71 if (ber_enclen(o, len, 1, 1) != 1)
73 if (odr_write(o, (unsigned char*) tmp.c + a, len) < 0)
76 fprintf(stderr, "[val=%d]", val);
82 * Returns: Number of bytes read or 0 if no match, -1 if error.
84 int ber_decinteger(const unsigned char *buf, int *val, int max)
86 const unsigned char *b = buf;
88 int res, len, remains;
89 union { int i; unsigned char c[sizeof(int)]; } tmp;
91 if ((res = ber_declen(b, &len, max)) < 0)
93 if (len+res > max || len < 0) /* out of bounds or indefinite encoding */
95 if (len > (int) sizeof(int)) /* let's be reasonable, here */
99 remains = sizeof(int) - len;
100 memcpy(tmp.c + remains, b, len);
105 memset(tmp.c, fill, remains);
110 fprintf(stderr, "[val=%d]", *val);