已知汉字如何求内码?已知内码如何求汉字?

解决方案 »

  1.   

    回复错了:
    比如说 “安 ”它的内码转化成十六进的为B0B2,如何写个函数,输入字符串“安”就能返回这个十六进制
    同理 已知十六进制B0B2如何写个函数,输入它之后就能显示“安”
      

  2.   

    既然是求代码,那就不再废话了,直接上代码: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");
        }
    }
      

  3.   


    java.net.URLEncoder.encode("安", "GBK").replace("%", "")