62,614
社区成员
发帖
与我相关
我的任务
分享
java.net.URLEncoder.encode("安", "GBK").replace("%", "")
public class Test3 {
public static void main(String[] args) {
System.out.println(ChineseUtil.toGBKHex('安'));
System.out.println(ChineseUtil.hex2GBK("b0b2"));
}
}
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
public class ChineseUtil {
private final static char[] HEX = "0123456789abcdef".toCharArray();
private final static Charset GBK_CHARSET = Charset.forName("GBK");
public static String toGBKHex(char c) {
CharsetEncoder enc = GBK_CHARSET.newEncoder();
CharBuffer cb = CharBuffer.allocate(1);
cb.append(c);
cb.flip();
try {
return toHex(enc.encode(cb).array());
} catch (CharacterCodingException e) {
e.printStackTrace();
return null;
}
}
public static String toHex(byte[] bys) {
if(bys == null) {
return null;
}
if(bys.length == 0) {
return "";
}
char[] chs = new char[bys.length * 2];
for(int i = 0, k = 0; i < bys.length; i++) {
chs[k++] = HEX[(bys[i] >>> 4) & 0xf];
chs[k++] = HEX[bys[i] & 0xf];
}
return new String(chs);
}
public static String hex2GBK(String hex) {
byte[] bys = hex2Bytes(hex);
ByteBuffer bb = ByteBuffer.wrap(bys);
return GBK_CHARSET.decode(bb).toString();
}
public static byte[] hex2Bytes(String hex) {
if(hex == null) {
return null;
}
if(hex.length() == 0) {
return new byte[0];
}
if(hex.length() % 2 != 0) {
throw new IllegalArgumentException("hex string is incorrect");
}
char[] chs = hex.toCharArray();
byte[] bys = new byte[chs.length / 2];
for(int i = 0, k = 0; i < bys.length; i++) {
bys[i] = (byte)((hex2Byte(chs[k++]) << 4) | hex2Byte(chs[k++]));
}
return bys;
}
public static int hex2Byte(char ch) {
if(ch >= '0' && ch <= '9') {
return ch - '0';
}
if(ch >= 'a' && ch <= 'f') {
return ch - 'a' + 10;
}
if(ch >= 'A' && ch <= 'F') {
return ch - 'A' + 10;
}
throw new IllegalArgumentException(ch + " is not hex character");
}
}