public int decodeInteger(boolean implicit) throws Asn1Exception {
        int retValue;

        //
        // There must be at least 2 bytes available
        //
        if (residualLength < 2)
            throw new Asn1Exception("Attempt to read past end of stream");

        //
        // Validate the tag for an explicit value
        //
        if (!implicit && stream[next] != ASN1_INTEGER)
            throw new Asn1Exception("Field at offset "+next+" is not an INTEGER");

        if ((stream[next]&ASN1_CONSTRUCTED) != 0)
            throw new Asn1Exception("INTEGER must not be a constructed field");

        next++;
        residualLength--;

        //
        // Decode the field length
        //
        int length = decodeLength();

        if (length > 4)
            throw new Asn1Exception("Value length "+length+" is not valid");

        if (length > residualLength)
            throw new Asn1Exception("Attempt to read past end of stream");

        //
        // Decode the integer value
        //
        if (stream[next] >= 0)
            retValue = 0;
        else
            retValue = -1;

        for (int i=0; i<length; i++)
            retValue = (retValue<<8)|((int)stream[next++]&0xff);

        residualLength -= length;
        return retValue;
    }