我的C#入门之路_Day4
这次的博客记录的是写crc校验码的过程。
过程十分坎坷,好不容易快整完了结果虚拟机崩了,程序也没了,只好重新来过。。。
首先是控制台应用程序的代码。
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using System.IO; 7 8 9 namespace ConsoleApplication1 10 { 11 class Program 12 { 13 static Int64 a(int length, byte[] data) 14 { 15 Int64 CRCtemp = 65535; 16 int j = 0; 17 int chr = 0; 18 int chr1 = 0; 19 for (int y = 0; y < length; y++) 20 { 21 chr = (int)CRCtemp & 255; 22 chr = chr ^ data[j]; 23 CRCtemp = CRCtemp & 0xff00; 24 CRCtemp = CRCtemp + chr; 25 for (int i = 0; i < 8; i++) 26 { 27 if ((CRCtemp & 0x01) == 1) 28 { 29 CRCtemp = CRCtemp >> 1; 30 CRCtemp = CRCtemp ^ 0xA001; 31 32 } 33 else 34 { 35 CRCtemp = CRCtemp >> 1; 36 } 37 } 38 j += 1; 39 } 40 chr = (int)CRCtemp & 0xff; 41 chr1 = (int)CRCtemp & 0xff00; 42 CRCtemp = chr << 8 | chr1 >> 8; 43 return CRCtemp; 44 } 45 static void Main(string[] args) 46 { 47 string str; 48 Console.WriteLine("input your file please:"); 49 str = Console.ReadLine(); 50 FileStream fs = new FileStream(str, FileMode.Open); 51 byte[] bt = new byte[1000]; 52 int i = 0; 53 BinaryReader br = new BinaryReader(fs); 54 while(br.PeekChar() >= 0) 55 { 56 bt[i] = br.ReadByte(); 57 i++; 58 } 59 Int64 result; 60 result = a(i, bt); 61 Console.WriteLine("the result is 0x" + result); 62 63 64 65 } 66 } 67 }
其中的算法是读了许久的实验要求,又百度了好久才看懂的。。。
然后是测试文件“123.txt”的内容:
crccalculation
最后是运行结果:
(ps:字可能有些小了)
控制台应用代码:
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Threading.Tasks; 9 using System.Windows.Forms; 10 using System.Diagnostics; 11 using System.IO; 12 13 namespace WindowsFormsApplication1 14 { 15 public partial class Form1 : Form 16 { 17 public Form1() 18 { 19 InitializeComponent(); 20 } 21 22 private void button1_Click(object sender, EventArgs e) 23 { 24 string str; 25 Process cdb = new Process(); 26 ProcessStartInfo startInfo = new ProcessStartInfo(); 27 startInfo.FileName = @"C:\Users\lenovo\Documents\Visual Studio 2013\Projects\ConsoleApplication1\ConsoleApplication1\bin\Debug\ConsoleApplication1.exe"; 28 startInfo.UseShellExecute = false; 29 startInfo.CreateNoWindow = true; 30 startInfo.RedirectStandardError = true; 31 startInfo.RedirectStandardInput = true; 32 startInfo.RedirectStandardOutput = true; 33 cdb.StartInfo = startInfo; 34 cdb.Start(); 35 cdb.StartInfo.Arguments = textBox1.Text; 36 textBox3.Text = cdb.StandardOutput.ReadLine(); 37 cdb.Refresh(); 38 cdb.Close(); 39 40 41 42 } 43 44 private void textBox2_TextChanged(object sender, EventArgs e) 45 { 46 47 48 } 49 } 50 }
结果: