📄 protectedcrc.java
字号:
package designPatterns;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutput;import java.io.ObjectOutputStream;import java.io.Serializable;import java.io.StreamCorruptedException;public class ProtectedCrc { private int crc; private byte[] bytearr; public void storeObj(Serializable object) throws IOException { // Serialize to a byte array ObjectOutput out; ByteArrayOutputStream bos = new ByteArrayOutputStream() ; out = new ObjectOutputStream(bos) ; out.writeObject(object); out.close(); bytearr = bos.toByteArray(); crc = calcCrc(); } public Serializable getObj() throws StreamCorruptedException, IOException, ClassNotFoundException { // Deserialize from a byte array ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytearr)); Serializable obj = (Serializable) in.readObject(); in.close(); return obj; } public boolean checkCrc() { return (calcCrc() == crc); } private int calcCrc() { int crc = 0x0; crc = 0xFFFFFFFF; // initial contents of shift register int poly = 0xEDB88320; // polynomial for (int b = 0; b < bytearr.length; b++) { int temp = (crc ^ bytearr[b]) & 0xff; // read 8 bits one at a time for (int i = 0; i < 8; i++) { if ((temp & 1) == 1) temp = (temp >>> 1) ^ poly; else temp = (temp >>> 1); } crc = (crc >>> 8) ^ temp; } crc = crc ^ 0xffffffff; return crc; }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -