Jump to content

UTF-8 encode and decode: Difference between revisions

m
→‎{{header|Java}}: refactor out encode and decode functions
(added java)
m (→‎{{header|Java}}: refactor out encode and decode functions)
Line 164:
 
public class UTF8EncodeDecode {
public static byte[] utf8encode(int codepoint) throws UnsupportedEncodingException {
return new String(new int[]{codepoint}, 0, 1).getBytes("UTF-8");
}
public static int utf8decode(byte[] bytes) throws UnsupportedEncodingException {
return new String(bytes, "UTF-8").codePointAt(0);
}
public static final void main(String[] args) throws UnsupportedEncodingException {
System.out.printf("%-7s %-43s %7s\t%s\t%7s\n", "Char", "Name", "Unicode", "UTF-8 encoded", "Decoded");
Line 169 ⟶ 175:
String name = Character.getName(codepoint);
String string = new String(new int[]{codepoint}, 0, 1);
byte[] encoded = string.getBytesutf8encode("UTF-8"codepoint);
Formatter formatter = new Formatter();
for (byte b : encoded) {
Line 175 ⟶ 181:
}
String encodedHex = formatter.toString();
int decoded = new Stringutf8decode(encoded, "UTF-8").codePointAt(0);
System.out.printf("%-7s %-43s U+%04X\t%-12s\tU+%04X\n", string, name, codepoint, encodedHex, decoded);
}
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.