62,614
社区成员
发帖
与我相关
我的任务
分享
public class StringCoder
{
static char[] hexCharArray = {'0','1','2','3',
'4','5','6','7',
'8','9','A','B',
'C','D','E','F'};
public String transform(String src)
{
src = "%e6%a1%8c%e9%9d%a2";
String [] unitArray = src.toUpperCase().split("%");
char [] chars = new char[(unitArray.length - 1) / 2];
int leng = 0;
for (int i = 1; i < unitArray.length; i += 2)
{
byte b1 = hexStringToByte(unitArray[i]);
byte b2 = hexStringToByte(unitArray[i + 1]);
chars[leng++] = (char)((b1 << 8) | (b2 & 0xff));
}
String dest = new String(chars);
return dest;
}
public byte hexStringToByte(String hexStr)
{
System.out.println(hexStr);
int data = 0;
char high = hexStr.charAt(0);
char low = hexStr.charAt(1);
int index = -1;
for (int i = 0; i < hexCharArray.length; i++)
{
if (hexCharArray[i] == high)
{
index = i;
break;
}
}
data += index * 16;
index = -1;
for (int i = 0; i < hexCharArray.length; i++)
{
if (hexCharArray[i] == low)
{
index = i;
break;
}
}
data += index;
return (byte)data;
}
public static void main(String [] args) throws Exception
{
String rs = new StringCoder().transform(null);
System.out.println(rs);
}
}
public static String decodeUTF8(String src)
{
src = "%e6%a1%8c%e9%9d%a2";
String [] unitArray = src.split("%");
char [] chars = new char[unitArray.length];
int leng = 0;
for (int i = 1; i < unitArray.length;)
{
int data = 0;
byte [] bytes = new byte[5];
bytes[0] = hexStringToByte(unitArray[i]);
int byteNum = getLeftCountOf1InByte(bytes[0]);
for (int j = 1; j < byteNum; j++)
{
bytes[j] = (byte)(hexStringToByte(unitArray[i + j]) & 0x3F);
}
bytes[0] = maskFirstByte(bytes[0]);
int byteCount = 0;
for (int j = byteNum - 1; j >= 0; j--)
{
data |= bytes[j] << (6 * byteCount);
byteCount++;
}
chars[leng++] = (char)data;
i += byteNum;
}
return new String(chars,0,leng);
}
public static byte hexStringToByte(String hexStr)
{
hexStr = hexStr.toUpperCase();
char high = hexStr.charAt(0);
char low = hexStr.charAt(1);
int highVal = 0;
if (high >= '0' && high <= '9')
{
highVal = high - '0';
}
else
{
highVal = 10 + (high - 'A');
}
int lowVal = 0;
if (low >= '0' && low <= '9')
{
lowVal = low - '0';
}
else
{
lowVal = 10 + (low - 'A');
}
return (byte)((highVal << 4) | lowVal);
}
public static int getLeftCountOf1InByte(byte b)
{
int count = 0;
int mask = 1 << 7;
for (int i = 0; i < 8; i++)
{
if ((b & mask) == 0)
{
break;
}
else
{
count++;
mask >>= 1;
}
}
return count;
}
private static byte maskFirstByte(byte b)
{
int mask = 1 << 7;
for (int i = 0; i < 8; i++)
{
if ((b & mask) == 0)
{
break;
}
else
{
b &= ~mask;
mask >>= 1;
}
}
return (byte)b;
}
public static void main(String [] args) throws Exception
{
String rs = new StringCoder().decodeUTF8(null);
System.out.println(rs);
}