?? 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 + -