public void TestCalculateCRC32_SeedGetsReset() { CRC crcCalculator = new CRC(CRCEnum.CRC32); string retCRC = crcCalculator.CalculateCRC(testStringBytes); Assert.AreEqual("CBF43926", retCRC); retCRC = crcCalculator.CalculateCRC(System.Text.Encoding.ASCII.GetBytes("123")); Assert.AreNotEqual("CBF43926", retCRC); retCRC = crcCalculator.CalculateCRC(testStringBytes); Assert.AreEqual("CBF43926", retCRC); }
public void TestCalculateCRC32_ASCIIString_FullArray() { CRC crcCalculator = new CRC(CRCEnum.CRC32); string retCRC = crcCalculator.CalculateCRC(testStringBytes); Assert.AreEqual("CBF43926", retCRC); }
static int Main(string[] args) { if (args.Length == 0) { Console.WriteLine("Usage: crc <file_path>"); return(1); } string filePath = args[0]; byte[] fileContents = null; try { fileContents = File.ReadAllBytes(filePath); } catch (Exception e) { Console.WriteLine("There was a problem reading the file."); Console.WriteLine(e.Message); return(1); } Console.WriteLine("{0:X4}", CRC.CalculateCRC(fileContents)); CRC.AddCrc(filePath); return(0); }
private void CalculateCRC_button_Click_1(object sender, EventArgs e) { if (!IsValidCRC()) { return; } var fromBase = Convert.ToInt32(comboBox1.Text); long poly = Convert.ToInt64(poly_textBox.Text, 2); crc = new CRC(poly); _inputMessages.Clear(); _CRCs.Clear(); _isCorrect.Clear(); message2_textBox.Text = ""; CalculatedCRC_textBox.Text = ""; InputCRC_textBox.Text = ""; var stringMessages = message16_textBox.Text.Split(); foreach (var str in stringMessages) { _inputMessages.Add(Convert.ToInt64(str, fromBase)); message2_textBox.Text += Convert.ToString(_inputMessages.Last(), 2) + " "; // Получение CRC кода входного блока данных _CRCs.Add(crc.CalculateCRC(_inputMessages.Last())); CalculatedCRC_textBox.Text += Convert.ToString(_CRCs.Last(), 2) + " "; InputCRC_textBox.Text += Convert.ToString(_CRCs.Last(), 2) + " "; } }
static int Main(string[] args) { if (args.Length == 0) { Console.WriteLine("Usage: crc <file_path>"); return(1); } string filePath = args[0]; string fileContents = null; try { using (StreamReader reader = File.OpenText(filePath)) { fileContents = reader.ReadToEnd(); } } catch (Exception e) { Console.WriteLine("There was a problem reading the file."); return(1); } Console.WriteLine("{0:X4}", CRC.CalculateCRC(fileContents)); return(0); }
private ulong CalcCRC(String type, byte[] buffer) { byte[] temp = new byte[buffer.Length + 4]; byte[] tempType = System.Text.Encoding.UTF8.GetBytes(type); Array.Copy(tempType, temp, 4); Array.Copy(buffer, 0, temp, 4, buffer.Length); CRC c = new CRC(); return(c.CalculateCRC(temp, temp.Length)); }
public static void IsZipSameAsDir(Stream archiveFile, string directory, ZipArchiveMode mode, bool requireExplicit, bool checkTimes) { int count = 0; using (ZipArchive archive = new ZipArchive(archiveFile, mode)) { List <FileData> files = FileData.InPath(directory); Assert.All <FileData>(files, (file) => { count++; string entryName = file.FullName; if (file.IsFolder) { entryName += Path.DirectorySeparatorChar; } ZipArchiveEntry entry = archive.GetEntry(entryName); if (entry == null) { entryName = FlipSlashes(entryName); entry = archive.GetEntry(entryName); } if (file.IsFile) { Assert.NotNull(entry); long givenLength = entry.Length; var buffer = new byte[entry.Length]; using (Stream entrystream = entry.Open()) { ReadAllBytes(entrystream, buffer, 0, buffer.Length); #if NETCOREAPP uint zipcrc = entry.Crc32; Assert.Equal(CRC.CalculateCRC(buffer), zipcrc); #endif if (file.Length != givenLength) { buffer = NormalizeLineEndings(buffer); } Assert.Equal(file.Length, buffer.Length); ulong crc = CRC.CalculateCRC(buffer); Assert.Equal(file.CRC, crc.ToString()); } if (checkTimes) { const int zipTimestampResolution = 2; // Zip follows the FAT timestamp resolution of two seconds for file records DateTime lower = file.LastModifiedDate.AddSeconds(-zipTimestampResolution); DateTime upper = file.LastModifiedDate.AddSeconds(zipTimestampResolution); Assert.InRange(entry.LastWriteTime.Ticks, lower.Ticks, upper.Ticks); } Assert.Equal(file.Name, entry.Name); Assert.Equal(entryName, entry.FullName); Assert.Equal(entryName, entry.ToString()); Assert.Equal(archive, entry.Archive); } else if (file.IsFolder) { if (entry == null) //entry not found { string entryNameOtherSlash = FlipSlashes(entryName); bool isEmpty = !files.Any( f => f.IsFile && (f.FullName.StartsWith(entryName, StringComparison.OrdinalIgnoreCase) || f.FullName.StartsWith(entryNameOtherSlash, StringComparison.OrdinalIgnoreCase))); if (requireExplicit || isEmpty) { Assert.Contains("emptydir", entryName); } if ((!requireExplicit && !isEmpty) || entryName.Contains("emptydir")) { count--; //discount this entry } } else { using (Stream es = entry.Open()) { try { Assert.Equal(0, es.Length); } catch (NotSupportedException) { try { Assert.Equal(-1, es.ReadByte()); } catch (Exception) { Console.WriteLine("Didn't return EOF"); throw; } } } } } }); Assert.Equal(count, archive.Entries.Count); } }
/// <summary> /// Assembles our packet and transmits it over the current COM port /// </summary> /// <param name="command">Raman command as per API</param> /// <param name="write">1 for a write, 0 for a read</param> /// <param name="dataT">Data to be sent for a write, null for a read</param> private void SendData(DeviceCommand command, int write, byte[] dataT) { recieved_data_buffer = new byte[1024]; // Re-initialize our return buffer recieved_data_buffer_index = 0; byte[] cmd = new byte[CMDOverhead + dataT.Length]; byte[] data = new byte[cmd.Length + 1]; int dataArrayLength = dataT.Length; dataArrayLength = dataArrayLength + 1; // Assemble command information cmd[0] = 0; cmd[1] = (byte)dataArrayLength; if (write > 0) { byte temp = (byte)(command + 0x80); cmd[2] = temp; } else { cmd[2] = (byte)command; } if (dataArrayLength > 1) { for (int i = 0; i < dataT.Length; i++) { cmd[i + 3] = dataT[i]; } cmd[3 + dataArrayLength - 1] = Crc.CalculateCRC(cmd, 3 + dataT.Length); } else { cmd[3] = Crc.CalculateCRC(cmd, 3); } // add command data to packet cmd.CopyTo(data, 1); // add delimiters to packet data[0] = (byte)'<'; data[data.Length - 1] = (byte)'>'; // Send data out the serial port if (serial.IsOpen) { try { // Send the binary data out the port foreach (byte byteval in data) { byte[] _byteval = new byte[] { byteval }; // need to convert byte serial.Write(_byteval, 0, 1); Thread.Sleep(1); } // Print data to debug terminal dateStampOutput(); textBox_Output.Text += "Data Sent: "; for (int j = 0; j < data.Length; j++) { textBox_Output.Text += data[j].ToString() + " "; } textBox_Output.Text += System.Environment.NewLine; } catch (Exception ex) { // Print data to debug terminal dateStampOutput(); textBox_Output.Text += "Data FAILED to send: "; for (int j = 0; j < data.Length; j++) { textBox_Output.Text += data[j].ToString() + " "; } textBox_Output.Text += System.Environment.NewLine; } } else { // Print data to debug terminal dateStampOutput(); textBox_Output.Text += "Serial port is closed. Cannot Send data."; textBox_Output.Text += System.Environment.NewLine; } enableAllAcquisitionButtons(); }
public static void IsZipSameAsDir(Stream archiveFile, String directory, ZipArchiveMode mode, Boolean dontRequireExplicit, Boolean dontCheckTimes) { int count = 0; using (ZipArchive archive = new ZipArchive(archiveFile, mode)) { var allFilesInDir = FileData.InPath(directory); foreach (var file in allFilesInDir) { count++; String entryName = file.FullName; if (file.IsFolder) { entryName += Path.DirectorySeparatorChar; } ZipArchiveEntry entry = archive.GetEntry(entryName); if (entry == null) { entryName = FlipSlashes(entryName); entry = archive.GetEntry(entryName); } if (file.IsFile) { try { Assert.NotNull(entry); } catch (Exception) { Console.WriteLine("File Entry {0} in directory but not archive: {1}", entryName, file.FullName); throw; } Int64 givenLength = entry.Length; var buffer = new byte[entry.Length]; using (Stream entrystream = entry.Open()) { entrystream.Read(buffer, 0, buffer.Length); String crc = CRC.CalculateCRC(buffer); Assert.Equal(file.Length, givenLength); Assert.Equal(file.CRC, crc); } if (!dontCheckTimes) { Double offBy = (file.LastModifiedDate - entry.LastWriteTime.DateTime).TotalSeconds; Assert.True( (offBy >= -2 && offBy <= 2) || // Temporary adjustment for active issue 1326 ((offBy >= 3598 && offBy <= 3602)), String.Format("{0}, {1}, {2}", file.LastModifiedDate.ToString(), entry.LastWriteTime.DateTime.ToString(), file.FullName)); } Assert.Equal(file.Name, entry.Name); Assert.Equal(entryName, entry.FullName); Assert.Equal(entryName, entry.ToString()); Assert.Equal(archive, entry.Archive); } else if (file.IsFolder) { if (entry == null) //entry not found { string entryNameOtherSlash = FlipSlashes(entryName); Boolean isEmtpy = !allFilesInDir.Any( f => f.IsFile && (f.FullName.StartsWith(entryName, StringComparison.OrdinalIgnoreCase) || f.FullName.StartsWith(entryNameOtherSlash, StringComparison.OrdinalIgnoreCase))); if ((!dontRequireExplicit || isEmtpy) && !entryName.Contains("emptydir")) { Assert.True(false, String.Format("Folder Entry {0} in directory but not archive: {1}", entryName, directory)); } if ((dontRequireExplicit && !isEmtpy) || entryName.Contains("emptydir")) { count--; //discount this entry } } else { using (Stream es = entry.Open()) { try { Assert.Equal(0, es.Length); } catch (NotSupportedException) { try { Assert.Equal(-1, es.ReadByte()); } catch (Exception) { Console.WriteLine("Didn't return EOF"); throw; } } } } } } Assert.Equal(count, archive.Entries.Count); } }
/// <summary> /// Assemble packet and send off to device. /// </summary> /// <param name="command"></param> /// <param name="write"></param> /// <param name="dataT"></param> /// <returns></returns> private async Task WriteAsync(DeviceCommand command, int write, byte[] dataT) { Task <UInt32> storeAsyncTask; byte[] cmd = new byte[CMDOverhead + dataT.Length]; byte[] data = new byte[cmd.Length + 1]; int dataArrayLength = dataT.Length; dataArrayLength = dataArrayLength + 1; // Assemble command information cmd[0] = 0; cmd[1] = (byte)dataArrayLength; if (write > 0) { byte temp = (byte)(command + 0x80); cmd[2] = temp; } else { cmd[2] = (byte)command; } if (dataArrayLength > 1) { for (int i = 0; i < dataT.Length; i++) { cmd[i + 3] = dataT[i]; } cmd[3 + dataArrayLength - 1] = Crc.CalculateCRC(cmd, 3 + dataT.Length); } else { cmd[3] = Crc.CalculateCRC(cmd, 3); } // add command data to packet cmd.CopyTo(data, 1); // add delimiters to packet data[0] = (byte)'<'; data[data.Length - 1] = (byte)'>'; // Print data to debug terminal dateStampOutput(); outputTextBox.Text += "Data Sent: "; for (int j = 0; j < data.Length; j++) { outputTextBox.Text += data[j].ToString() + " "; } outputTextBox.Text += System.Environment.NewLine; // Load the packet into the dataWriter object dataWriterObject.WriteBytes(data); // Launch an async task to complete the write operation storeAsyncTask = dataWriterObject.StoreAsync().AsTask(); UInt32 bytesWritten = await storeAsyncTask; if (bytesWritten > 0) { string status_Text = ", "; string debug_text = ""; status_Text += bytesWritten.ToString(); status_Text += " bytes written successfully!"; for (int i = 0; i < data.Length; i++) { debug_text = debug_text + data[i].ToString() + " "; } debug_text = debug_text + status_Text; Debug.WriteLine(debug_text); } }
private ulong CalcCRC(String type, byte[] buffer) { byte[] temp = new byte[buffer.Length + 4]; byte[] tempType = System.Text.Encoding.UTF8.GetBytes(type); Array.Copy(tempType, temp, 4); Array.Copy(buffer, 0, temp, 4, buffer.Length); CRC c = new CRC(); return c.CalculateCRC(temp, temp.Length); }