读懂代码需要了解以下几个知识点:
1、GB2312编码
2、RandomAccessFile文件指针操作
offset = (94 * (区码 - 1) + (位码 - 1)) * 32;
主要思路:计算出汉字在汉字库中的区位码,计算出偏移量offset,利用文件指针读取汉字库文件。
//-------------------
需要读取16*16汉字库文件
链接:https://pan.baidu.com/s/1t-nDsVYTcFgiVWgGtTdUAA
提取码:zlcc
//-------------------
实现代码:
import java.io.File;
import java.io.RandomAccessFile;
public class Hz {
//获取区位码
private static String bytes2HexString(byte b) {
return bytes2HexString(new byte[]{b});
}
private 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 int[] getLocation(String str) throws Exception {
byte[] bs = str.getBytes("GB2312");
int[] s = new int[str.length() * 2];
for (int i = 0; i < bs.length; i++) {
int a = Integer.parseInt(bytes2HexString(bs[i]), 16);
s[i] = (a - 0x80 - 0x20);
}
return s;
}
public static void Print(String str) throws Exception {
File file = new File("hzk16");
RandomAccessFile raf = new RandomAccessFile(file, "rw");
int i, j, k;
int offset;
int flag;
byte[] buffer = new byte[32];
char[] key = {
0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01
};
if (!file.canRead()) {
System.out.println("err hzk16\n");
return;
}
for (int a = 0; a < str.length()*2; a+=2) {
int[] location = getLocation(str);
offset = (94 * (location[a] - 1) + (location[a+1]- 1)) * 32;
System.out.println(offset);
raf.seek(offset);
raf.read(buffer, 0, 31);
// for (int l = 0; l < buffer.length; l++) {
System.out.printf("%B",buffer[l]);
// System.out.println(buffer[l]);
// }
for (k = 0; k < 16; k++) {
for (j = 0; j < 2; j++) {
for (i = 0; i < 8; i++) {
flag = buffer[k * 2 + j] & key[i];
if (flag > 1) System.out.print("● ");
else System.out.print("○ ");
}
}
System.out.print("\n");
}
System.out.print("uchar code key[32] = {");
for (k = 0; k < 31; k++) {
System.out.printf("0x%02X,", buffer[k]);
}
System.out.printf("0x%02X};\n", buffer[31]);
System.out.print("\n");
}
raf.close();
}
}
运行:
@Test
public void hz() throws Exception {
Hz.Print("汉字");
}
结果:
76000
○ ○ ○ ○ ○ ○ ○ ○ ○ ○ ○ ○ ○ ○ ○ ○
○ ● ○ ○ ○ ○ ○ ○ ○ ○ ○ ○ ● ○ ○ ○
○ ○ ● ● ○ ● ● ○ ● ● ● ● ● ● ○ ○
○ ○ ○ ● ○ ○ ○ ○ ○ ○ ○ ○ ● ○ ○ ○
● ○ ○ ○ ○ ○ ● ○ ○ ○ ○ ○ ● ○ ○ ○
○ ● ● ○ ○ ○ ● ○ ○ ○ ○ ○ ● ○ ○ ○
○ ○ ● ○ ○ ○ ● ○ ○ ○ ○ ● ○ ○ ○ ○
○ ○ ○ ○ ● ○ ○ ○ ○ ○ ○ ● ○ ○ ○ ○
○ ○ ○ ● ○ ○ ○ ○ ○ ○ ● ○ ○ ○ ○ ○
○ ○ ● ○ ○ ○ ○ ○ ● ○ ● ○ ○ ○ ○ ○
● ● ● ○ ○ ○ ○ ○ ○ ● ○ ○ ○ ○ ○ ○
○ ○ ● ○ ○ ○ ○ ○ ● ○ ● ○ ○ ○ ○ ○
○ ○ ● ○ ○ ○ ○ ○ ○ ○ ○ ● ○ ○ ○ ○
○ ○ ● ○ ○ ○ ● ○ ○ ○ ○ ○ ● ○ ○ ○
○ ○ ● ○ ○ ● ○ ○ ○ ○ ○ ○ ● ● ● ○
○ ○ ○ ○ ● ○ ○ ○ ○ ○ ○ ○ ○ ○ ○ ○
uchar code key[32] = {0x00,0x00,0x40,0x08,0x37,0xFC,0x10,0x08,0x82,0x08,0x62,0x08,0x22,0x10,0x09,0x10,0x11,0x20,0x20,0xA0,0xE0,0x40,0x20,0xA0,0x21,0x10,0x22,0x08,0x24,0x0E,0x08,0x00};
进程已结束,退出代码0