这几天做一切词程序,想获得汉字的区位码,但不知如何做,还请高人指点谢谢

解决方案 »

  1.   

    String str = "天津"
    byte[] bs  = str.getBytes("GBK");bs 里面就是!
      

  2.   

    整了尽一个小时,郁闷,睡觉.
    public static String bytes2HexString(byte b) {
    return bytes2HexString(new byte[] { b });
    } public static String bytes2HexString(byte[] b) {
    String ret = "";
    for (int i = 0; i < b.length; i++) {
    String hex = Integer.toHexString(b[i] & 0xFF);
    if (hex.length() == 1) {
    hex = '0' + hex;
    }
    ret += hex.toUpperCase();
    }
    return ret;
    } public static void main(String[] args) throws UnsupportedEncodingException {
    String str = "孙";
    byte[] bs = str.getBytes("GB2312");
    String s = "";
    for (int i = 0; i < bs.length; i++) {
    int a = Integer.parseInt(bytes2HexString(bs[i]), 16);
    s += (a - 0x80 - 0x20) + "";
    }
    System.out.println(s);
    }
      

  3.   

    str.getBytes("GB2312");
    取的是机内码
    减 0x80 国际码
    减 0x20 区位码
      

  4.   

    先获得某个字的 GB2312 码,比如“啊”为 B0A1把 B0A1 拆成 B0 和 A1,再减去 A0,即:0xB0 - 0xA0 = 0x10 = 16   (1)
    0xA1 - 0xA0 = 0x01 = 01   (2)(1)为区码,从 01~94,汉字分布在 16 至 87 区
    (2)为位码,从 01~94再将 (1)*100 + (2) 就得到区位码了PS:汉字中最小的区位码就是“啊”字,从 1601 开始public class Test {
        public static void main(String[] args) throws Exception {
            String str = "啊";
            int[] quwei = getQuwei(str);
            for(int i : quwei) {
                System.out.printf("%04d%n", i);
            }
        }    public static int[] getQuwei(String str) throws Exception {
            byte[] b = str.getBytes("gb2312");
            int[] quwei = new int[b.length / 2];
            for(int i = 0, k = b.length / 2; i < k; i++) {
                quwei[i] = (((b[2 * i] - 0xA0) & 0xff) * 100) + ((b[2 * i + 1] - 0xA0) & 0xff);
            }
            return quwei;
        }
    }
      

  5.   

    给的这个程序,str改为啊,得到的是161,并非1601啊
      

  6.   

    9楼给的程序正确
    2楼给的程序,str输入啊,得到的是160,非1601