生活随笔
收集整理的這篇文章主要介紹了
GBK 汉字编码转换
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
/**
* 描述:漢字轉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 blocke.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轉成intint 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;
}
總結
以上是生活随笔為你收集整理的GBK 汉字编码转换的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。