Skip to content

Instantly share code, notes, and snippets.

@sebastianbenz
Created December 2, 2012 21:24
Show Gist options
  • Save sebastianbenz/4191140 to your computer and use it in GitHub Desktop.
Save sebastianbenz/4191140 to your computer and use it in GitHub Desktop.
Encoding Unicodes
public static String convertToJavaString(String theString, boolean useUnicode) {
int len = theString.length();
int bufLen = len * 2;
if (bufLen < 0) {
bufLen = Integer.MAX_VALUE;
}
StringBuffer outBuffer = new StringBuffer(bufLen);
for (int x = 0; x < len; x++) {
char aChar = theString.charAt(x);
// Handle common case first, selecting largest block that
// avoids the specials below
if ((aChar > 61) && (aChar < 127)) {
if (aChar == '\\') {
outBuffer.append('\\');
outBuffer.append('\\');
continue;
}
outBuffer.append(aChar);
continue;
}
switch (aChar) {
case ' ':
outBuffer.append(' ');
break;
case '\t':
outBuffer.append('\\');
outBuffer.append('t');
break;
case '\n':
outBuffer.append('\\');
outBuffer.append('n');
break;
case '\r':
outBuffer.append('\\');
outBuffer.append('r');
break;
case '\f':
outBuffer.append('\\');
outBuffer.append('f');
break;
case '\b':
outBuffer.append('\\');
outBuffer.append('b');
break;
case '\'':
outBuffer.append('\\');
outBuffer.append('\'');
break;
case '"':
outBuffer.append('\\');
outBuffer.append('"');
break;
default:
if (useUnicode && ((aChar < 0x0020) || (aChar > 0x007e))) {
outBuffer.append('\\');
outBuffer.append('u');
outBuffer.append(toHex((aChar >> 12) & 0xF));
outBuffer.append(toHex((aChar >> 8) & 0xF));
outBuffer.append(toHex((aChar >> 4) & 0xF));
outBuffer.append(toHex(aChar & 0xF));
} else {
outBuffer.append(aChar);
}
}
}
return outBuffer.toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment