in ch-commons-charset/src/main/java/com/cloudhopper/commons/charset/ModifiedUTF8Charset.java [225:273]
static public int encodeToByteArray(CharSequence charSeq, char[] charBuffer, int charOffset, int charLength, byte[] byteBuffer, int byteOffset) {
int c = 0;
int bytePos = byteOffset; // start at byte offset
int charPos = charOffset; // start at char offset
int charAbsLength = charPos + charLength;
if (charBuffer == null) {
if (charSeq == null) {
throw new IllegalArgumentException("Both charSeq and charBuffer cannot be null");
}
// use charSequence rather than charBuffer
charOffset = 0;
charAbsLength = charSeq.length();
}
// optimized method is only ascii chars used
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)))
break;
byteBuffer[bytePos++] = (byte) c;
}
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)) {
byteBuffer[bytePos++] = (byte) c;
} else if (c > 0x07FF) {
byteBuffer[bytePos++] = (byte) (0xE0 | ((c >> 12) & 0x0F));
byteBuffer[bytePos++] = (byte) (0x80 | ((c >> 6) & 0x3F));
byteBuffer[bytePos++] = (byte) (0x80 | (c & 0x3F));
} else {
byteBuffer[bytePos++] = (byte) (0xC0 | ((c >> 6) & 0x1F));
byteBuffer[bytePos++] = (byte) (0x80 | (c & 0x3F));
}
}
return (bytePos-byteOffset);
}