Skip to content

Instantly share code, notes, and snippets.

@MoshDev
Created May 7, 2014 20:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MoshDev/0e072c7a9bd9523d6467 to your computer and use it in GitHub Desktop.
Save MoshDev/0e072c7a9bd9523d6467 to your computer and use it in GitHub Desktop.
/**
*
* @author MErsan
*/
public class ArabicUnicode {
private final static char[] digits = {
'0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'a', 'b',
'c', 'd', 'e', 'f'
};
public static String decode(String s) {
if (s == null || s.length() <= 0) {
return null;
}
String[] strings = s.split("\\\\");
StringBuilder result = new StringBuilder(strings.length);
for (String h : strings) {
if (h != null && h.length() >= 5 && h.startsWith("u")) {
result.append((char) Integer.parseInt(h.substring(1, 5), 16));
if (h.length() > 5) {
result.append(h.substring(5, h.length()));
}
} else {
result.append(h);
}
}
return result.toString();
}
public static String encode(String text) {
if (text == null || text.length() <= 0) {
return null;
}
int textLen = text.length();
StringBuilder buffer = new StringBuilder(textLen * 4);
for (int i = 0; i < textLen; i++) {
char c = text.charAt(i);
if (c < 32 || c > 126) {
buffer.append(toUnsignedString(text.charAt(i)));
} else {
buffer.append(c);
}
}
return buffer.toString();
}
final static int shift = 4;
final static int mask = 15;
public static String toUnsignedString(int i) {
char[] buf = {'\\', 'u', '0', '0', '0', '0'};
int charPos = 6;
do {
buf[--charPos] = digits[i & mask];
i >>>= shift;
} while (i != 0);
return new String(buf);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment