static public int calculateByteLength(CharSequence charSeq, char[] charBuffer, int charOffset, int charLength) {
        int c = 0;
        int byteLength = 0;
        int charPos = charOffset;       // start at char offset
        int charAbsLength = charPos + charLength;
        
        if (charBuffer == null) {
            if (charSeq == null) {
                return 0;
            }
            // use charSequence rather than charBuffer
            charOffset = 0;
            charAbsLength = charSeq.length();
        }
        
        for (; charPos < charAbsLength; charPos++) {
            // optimized method for getting char to encode
            if (charBuffer != null) {
                c = charBuffer[charPos];
            } else {
                c = charSeq.charAt(charPos);
            }
            if ((c >= 0x0000) && (c <= 0x007F)) {
                byteLength++;
            } else if (c > 0x07FF) {
                byteLength += 3;
            } else {
                byteLength += 2;
            }
        }
        return byteLength;
    }
static public int calculateByteLength ( CharSequence charSeq , char [ ] charBuffer , int charOffset , int charLength ) { int c = 0 ; int byteLength = 0 ; int charPos = charOffset ; int charAbsLength = charPos + charLength ; if ( charBuffer == null ) { if ( charSeq == null ) { return 0 ; } charOffset = 0 ; charAbsLength = charSeq . length ( ) ; } for ( ; charPos < charAbsLength ; charPos ++ ) { if ( charBuffer != null ) { c = charBuffer [ charPos ] ; } else { c = charSeq . charAt ( charPos ) ; } if ( ( c >= 0x0000 ) && ( c <= 0x007F ) ) { byteLength ++ ; } else if ( c > 0x07FF ) { byteLength += 3 ; } else { byteLength += 2 ; } } return byteLength ; }
Highly efficient method for calculating the byte length of
a String if it was encoded as modified UTF-8 bytes. Since no byte array
is allocated just for calculating the byte length, this method can speed up
checks by 90% vs. something like s.getBytes("UTF8").length. This method
is adapted from JDK source code for DataOutputStream.java.
@param charSeq The optional character sequence to use for encoding rather
than the provided character buffer. It is always higher performance
to supply a char array vs. use a CharSequence.  Set to null if the
character array is supplied.
@param charBuffer The source char array to encode
@param charOffset The offset in the source char array to start encode from
@param charLength The length from the offset in the source char array to encode
@return The number of bytes required to represent the String as modified
UTF-8 encoded bytes.