java代码如下:
//将%e4%bd%a0转换为汉字
public static string unescape(string s) {
stringbuffer sbuf = new stringbuffer();
int l = s.length();
int ch = -1;
int b, sumb = 0;
for (int i = 0, more = -1; i < l; i++) {
/* get next byte b from url segment s */
switch (ch = s.charat(i)) {
case '%':
ch = s.charat(++i);
int hb = (character.isdigit((char) ch) ? ch - '0'
: 10 + character.tolowercase((char) ch) - 'a') & 0xf;
ch = s.charat(++i);
int lb = (character.isdigit((char) ch) ? ch - '0'
: 10 + character.tolowercase((char) ch) - 'a') & 0xf;
b = (hb << 4) | lb;
break;
case '+':
b = ' ';
break;
default:
b = ch;
}
/* decode byte b as utf-8, sumb collects incomplete chars */
if ((b & 0xc0) == 0x80) { // 10xxxxxx (continuation byte)
sumb = (sumb << 6) | (b & 0x3f); // add 6 bits to sumb
if (--more == 0)
sbuf.append((char) sumb); // add char to sbuf
} else if ((b & 0x80) == 0x00) { // 0xxxxxxx (yields 7 bits)
sbuf.append((char) b); // store in sbuf
} else if ((b & 0xe0) == 0xc0) { // 110xxxxx (yields 5 bits)
sumb = b & 0x1f;
more = 1; // expect 1 more byte
} else if ((b & 0xf0) == 0xe0) { // 1110xxxx (yields 4 bits)
sumb = b & 0x0f;
more = 2; // expect 2 more bytes
} else if ((b & 0xf8) == 0xf0) { // 11110xxx (yields 3 bits)
sumb = b & 0x07;
more = 3; // expect 3 more bytes
} else if ((b & 0xfc) == 0xf8) { // 111110xx (yields 2 bits)
sumb = b & 0x03;
more = 4; // expect 4 more bytes
} else /*if ((b & 0xfe) == 0xfc)*/{ // 1111110x (yields 1 bit)
sumb = b & 0x01;
more = 5; // expect 5 more bytes
}
/* we don't test if the utf-8 encoding is well-formed */
}
return sbuf.tostring();
}
public static void main(string[] args){
system.out.println(urltoutf8.toutf8string("你"));
system.out.println(urltoutf8.unescape("%e4%bd%a0%20%e5%a5%bd"));
}
}
%e4%bd%a0
你 好
如对本文有疑问, 点击进行留言回复!!
Android 4.0使用Kotlin调用C语言以及汇编语言
Java Class.forName()用法和newInstance()方法原理解析
网友评论