📄 jcrc.java
字号:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
* 循环冗余校验算法:
*1,预置一个16 位寄存器为0xFFFF(全1),称之为CRC寄存器。
*2,将数据帧中的第一个8位字节与CRC寄存器中的低字节进行异或运算,结果存会CRC寄存器。
*3,将CRC寄存器向右移一位,最高位填0,最低位移出并检测。
*4,如果最低位为0:重复第三步(下一次移位)。如果最低位为1:将CRC寄存器与一个预设的固定值(0xA001)进行异或运算。
*5,重复第三步和第四步直到8次移位。这样处理完了一个完整的八位。
*6,重复第2步到第5步来处理下一个八位,直到所有的字节处理结束。
*7,最终CRC寄存器的值就是CRC的值。
*/
public class JCRC extends JFrame implements ActionListener
{
JLabel label1,label2,label3,titles;
JTextField field1,field2,field3;
JPanel p1,p2,pp12,p3,pbt,pt;
JButton sends = new JButton("计算");
public JCRC()
{
super("循环冗余校验码模拟实验");
Container cont=getContentPane();
label1=new JLabel("CRC寄存器:");label2=new JLabel("CRC多项式:");label3=new JLabel("目的串:");
titles=new JLabel("循环冗余校验算法实验");
titles.setFont(new java.awt.Font("Serif", 0, 30));
field1=new JTextField(20);field2=new JTextField(20);field3=new JTextField(20);
p1=new JPanel();p2=new JPanel();p3=new JPanel();pbt=new JPanel();
pt=new JPanel();pp12=new JPanel();
pt.add(titles);
p1.add(label1);p1.add(field1);
p2.add(label2);p2.add(field2);
pp12.add(p1);pp12.add(p2);
pbt.add(sends);
p3.add(label3);p3.add(field3);
cont.setLayout(new GridLayout(4,1));
cont.add(pt);
cont.add(pp12);cont.add(pbt);cont.add(p3);
sends.addActionListener(this);
setBounds(200,200,450,400);
p1.setBackground(new Color(135,171,238));
p2.setBackground(new Color(135,171,238));
pp12.setBackground(new Color(135,171,238));
pt.setBackground(new Color(135,171,238));
pbt.setBackground(new Color(135,171,238));
p3.setBackground(new Color(135,171, 238));
setResizable(false);
setVisible(true);
}
public void actionPerformed(ActionEvent e) //算法实现部分
{
if(e.getSource()==sends)
{
try
{
String source, key, poly;
int source_bin,key_bin,crc;
source=field1.getText();
key =field2.getText();
source_bin=Integer.parseInt(source,2); //以第二个参数所指定的基将字符串参数分析为一个带符号的整数
key_bin =Integer.parseInt(key,2);
//移位可与等号(<<=或>>=或>>>=)组合使用
//运算符左边的值会移动由右边的值指定的位数,再将得到的结果赋回左边的值。
source_bin<<=(key.length()-1); //同等于 source_bin=source_bin<<(key.length()-1);
key_bin <<=(source.length()-1); //同等于 key_bin=key_bin<<(source.length()-1);
crc=source_bin;
int temp=1<<source.length()+key.length()-2;
for(int i=0;i<source.length();i++)
{
int flag=temp&source_bin ; // '&' 按位与运算
if(flag!=0)
{
source_bin=source_bin^key_bin; // '^' 按位异或运算
flag=0;
}
temp>>=1; //同等于 temp=temp>>1;
key_bin>>=1; //同等于 key_bin=key_bin>>1;
}
crc+=source_bin; //同等于 crc=crc+source_bin;
field3.setText(Integer.toBinaryString(crc)); //将 crcint形式的转换为二进制对应的表达形式
}
catch(Exception ex)
{
field3.setText("对不起,您的输入有误,请重新输入!");
}
}
}
public static void main(String[] args)
{
JCRC frames=new JCRC();
frames.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -