Utf8 { static public byte[] encode(int c) { if (c < 0x80) return new byte[] { (byte)c }; byte[] buf; if (c < 0x800) { buf = new byte[2]; buf[0] = (byte)((c >> 6) | (0x80 | 0x40)); } else if (c < 0x10000) { buf = new byte[3]; buf[0] = (byte)((c >> (2 * 6)) | (0x80 | 0x40 | 0x20)); } else { buf = new byte[4]; buf[0] = (byte)((c >> (3 * 6)) | (0x80 | 0x40 | 0x20 | 0x10)); } for (int i = buf.length - 1; i > 0; i--) { buf[i] = (byte)((c & 0x3F) | 0x80); c >>= 6; } return buf; } private  Utf8(); static byte[] encode(int c);  }
@Test public void testEncode() throws UnsupportedEncodingException { for (int i = 0; i < 0x10FFFF; i++) { if (Utf16.isSurrogate(i)) continue; char[] chars; if (i <= 0xFFFF) chars = new char[] { (char)i }; else chars = new char[] { Utf16.surrogate1(i), Utf16.surrogate2(i) }; Assert.assertEquals(Utf8.encode(i), new String(chars).getBytes("UTF-8")); } }