GBK 汉字编码转换

    技术2022-07-11  76

    /** * 描述:汉字转GBK码 * @param word * @return */ public String wordToGBk (String word) throws UnsupportedEncodingException { String[] wordArray; String GBK=""; wordArray = word.split(""); for (int i=0;i<wordArray.length;i++){ GBK += URLEncoder.encode(wordArray[i], “GBK”).replaceAll("\%",""); if (i != wordArray.length-1){ GBK += “,”; } } return GBK; }

    /** * 描述:GBK转汉字 * @param GBK * @return */ public String GBKToWord (String GBK){ String result = new String(); try { /*GBK转汉字*/ byte[] bytes = new byte[GBK.length() / 2]; for(int i = 0; i < bytes.length; i ++){ byte high = Byte.parseByte(GBK.substring(i * 2, i * 2 + 1), 16); byte low = Byte.parseByte(GBK.substring(i * 2 + 1, i * 2 + 2), 16); bytes[i] = (byte) (high << 4 | low); } result = new String(bytes, "gbk"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return result; } /** * 描述:汉字转字库信息 * @param * @return * @throws IOException */ public byte[] wordToByte(String word) throws IOException { //16*16点阵的汉字占用32个字节 byte[] cbuf = new byte[32]; try { //这个是取点阵的“位” //char[] key = {0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01}; byte[] bytes = word.getBytes("GB2312"); //这中写法是把byte转成int int segNum = bytes[0] & 0xff; int bitNum = bytes[1] & 0xff; //算出这个字在字库文件中的偏移量,注意32是表示16*16像素的字站32个字节 int offset = (94 * (segNum - 0xa0 - 1) + (bitNum - 0xa0 - 1)) * 32; /* System.out.println("offset = " + offset);*/ //读取点阵字库文件,需要按需修改为你电脑上实际字库的绝对地址 ClassPathResource classPathResource = new ClassPathResource("HZK16C"); InputStream inputStream = classPathResource.getInputStream(); //跳过offset个字节,读取汉字占用的32个字节 inputStream.skip(offset); inputStream.read(cbuf); }catch (Exception e){ e.printStackTrace(); } return cbuf; } public String BinaryToHexString(byte[] bytes){ String hexStr = "0123456789ABCDEF"; String result = ""; String hex = ""; for(int i=0;i<bytes.length;i++){ //字节高4位 hex = String.valueOf(hexStr.charAt((bytes[i]&0xF0)>>4)); //字节低4位 hex += String.valueOf(hexStr.charAt(bytes[i]&0x0F)); result +=hex; } return result; } /** * * @descripton 二进制字符串转Byte数组 * @author LP * @date 2020/6/28 17:04 * @return */ public byte[] BinaryToByte(String binStr){ String[] temp = binStr.split(","); byte[] b = new byte[temp.length]; for (int i = 0; i < b.length; i++) { b[i] = Long.valueOf(temp[i], 2).byteValue(); } return b; }
    Processed: 0.011, SQL: 9