byte[] utf8 String unicode

public static final String utf8_decode(byte[] utf8_bytes) throws java.io.UTFDataFormatException { return utf8_decode(utf8_bytes, 0, utf8_bytes.length); } public static final String utf8_decode(byte[] utf8_bytes, int start, int len) throws java.io.UTFDataFormatException { if (utf8_bytes == null) return null; int end = start + len; char[] unicode_chars = new char[len]; int i, counter = 0; try { for (i = start; i < end; i++) { byte b = utf8_bytes[i]; if ((b >> 7) == 0) { // read one byte unicode_chars[counter++] = (char) (b); } else if ((b >> 5) == (byte) 0xfe) { // read two bytes unicode_chars[counter] = (char) ((char) (b & 0x1f) << 6); unicode_chars[counter++] += utf8_bytes[++i] & 0x3f; } else if ((b >> 4) == (byte) 0xfe) { // read three bytes unicode_chars[counter] = (char) ((char) (b & 0xf) << 12); unicode_chars[counter] += (char) ((char) (utf8_bytes[++i] & 0x3f) << 6); unicode_chars[counter++] += utf8_bytes[++i] & 0x3f; } } return new String(unicode_chars, 0, counter); } catch (Exception ex) { throw new java.io.UTFDataFormatException(); } } public static final byte[] utf8_encode(String src) { if (src == null) return null; /** copy chars into array */ int len = src.length(); char[] chars = src.toCharArray(); byte[] bytes = new byte[len * 3]; int counter = 0; char c; for (int n = 0; n < len; n++) { c = chars[n]; if (c < 128) bytes[counter++] = (byte) c; else if ((c > 127) && (c < 2048)) { bytes[counter++] = (byte) ((c >> 6) | 192); bytes[counter++] = (byte) ((c & 63) | 128); } else { bytes[counter++] = (byte) ((c >> 12) | 224); bytes[counter++] = (byte) (((c >> 6) & 63) | 128); bytes[counter++] = (byte) ((c & 63) | 128); } } byte[] result = new byte[counter]; System.arraycopy(bytes, 0, result, 0, counter); bytes = null; chars = null; return result; }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值