1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.asn1new.util;
18
19 import org.apache.asn1new.ber.tlv.Value;
20
21
22 /***
23 * Parse and decode an Integer value.
24 *
25 * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
26 */
27 public class IntegerDecoder
28 {
29 private static final int[] MASK = new int[]{ 0x000000FF, 0x0000FFFF, 0x00FFFFFF, 0xFFFFFFFF};
30
31
32
33 /***
34 * Parse a byte buffer and send back an integer, controling
35 * that this number is in a specified interval.
36 * @param value The byte buffer to parse
37 * @param min Lowest value allowed, included
38 * @param max Highest value allowed, included
39 *
40 * @return An integer
41 *
42 * @throws IntegerDecoderException Thrown if the byte stream does not contains an integer
43 */
44 public static int parse( Value value, int min, int max ) throws IntegerDecoderException
45 {
46
47 int result = 0;
48
49 byte[] bytes = value.getData();
50
51 if ( bytes.length > 4 )
52 {
53 throw new IntegerDecoderException(
54 "The value is more than 4 bytes long. This is not allowed for an integer" );
55 }
56
57 for ( int i = 0; ( i < bytes.length ) && ( i < 5 ); i++ )
58 {
59 result = ( result << 8 ) | ( bytes[i] & 0x00FF );
60 }
61
62 if ( ( bytes[0] & 0x80 ) == 0x80 )
63 {
64 result = - ( ( ( ~ result ) + 1 ) & MASK[bytes.length - 1] );
65 }
66
67 if ( ( result >= min ) && ( result <= max ) )
68 {
69 return result;
70 }
71 else
72 {
73 throw new IntegerDecoderException( "The value is not in the range [" + min + ", " + max + "]" );
74 }
75 }
76
77 /***
78 * Parse a byte buffer and send back an integer
79 *
80 * @param value The byte buffer to parse
81 *
82 * @return An integer
83 *
84 * @throws IntegerDecoderException Thrown if the byte stream does not contains an integer
85 */
86 public static int parse( Value value ) throws IntegerDecoderException
87 {
88 return parse( value, Integer.MIN_VALUE, Integer.MAX_VALUE );
89 }
90 }