public FlakeReader(string path, Stream IO) { _path = path; _IO = IO != null ? IO : new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 0x10000); crc8 = new Crc8(); crc16 = new Crc16(); _framesBuffer = new byte[0x20000]; decode_metadata(); frame = new FlacFrame(PCM.ChannelCount); framereader = new BitReader(); //max_frame_size = 16 + ((Flake.MAX_BLOCKSIZE * PCM.BitsPerSample * PCM.ChannelCount + 1) + 7) >> 3); if (((int)max_frame_size * PCM.BitsPerSample * PCM.ChannelCount * 2 >> 3) > _framesBuffer.Length) { byte[] temp = _framesBuffer; _framesBuffer = new byte[((int)max_frame_size * PCM.BitsPerSample * PCM.ChannelCount * 2 >> 3)]; if (_framesBufferLength > 0) Array.Copy(temp, _framesBufferOffset, _framesBuffer, 0, _framesBufferLength); _framesBufferOffset = 0; } _samplesInBuffer = 0; if ((PCM.BitsPerSample != 16 && PCM.BitsPerSample != 24) || PCM.ChannelCount != 2 || (PCM.SampleRate != 44100 && PCM.SampleRate != 48000)) throw new Exception("invalid flac file"); samplesBuffer = new int[Flake.MAX_BLOCKSIZE * PCM.ChannelCount]; residualBuffer = new int[Flake.MAX_BLOCKSIZE * PCM.ChannelCount]; }
/// <summary>Calculates the CRC16 check-sum on specified portion of a buffer.</summary> /// <param name="data">Data buffer to perform check-sum on.</param> /// <param name="startIndex">Starts index in data buffer to begin check-sum.</param> /// <param name="length">Total number of bytes from <paramref name="startIndex">startIndex</paramref> to /// perform check-sum over.</param> /// <returns>Computed CRC16 checksum over the specified portion of the buffer.</returns> public static ushort Crc16Checksum(this byte[] data, int startIndex, int length) { Crc16 checksum = new Crc16(); checksum.Update(data, startIndex, length); return checksum.Value; }
void RunCrcTest(byte[] payload, ushort dataTypeSignature, ushort expectedCrc) { var payloadCrc = payload[0] | (payload[1] << 8); Assert.Equal(expectedCrc, payloadCrc); var actualCrc = Crc16.Add(dataTypeSignature, payload, 2, payload.Length - 2); Assert.Equal(expectedCrc, actualCrc); }
public void CheckCrc() { var origCrc = BitConverter.ToUInt16(_crc.Reverse().ToArray(), 0); var res = Crc16.ComputeChecksum(_data); if (res != origCrc) { throw new InvalidDataException("crc mismatch"); } }
public void Crc16_Ccitt() { string expected = "DF2E"; Crc16 actualCrc = Crc16.GetCcitt(); actualCrc.Append("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", true); string actual = actualCrc.Digest.ToString("X4"); Assert.AreEqual(expected, actual); }
/// <summary> /// * /// </summary> public override void ReadBitAllocation(Bitstream stream, Header header, Crc16 crc) { int length = get_allocationlength(header); allocation = stream.GetBitsFromBuffer(length); channel2_allocation = stream.GetBitsFromBuffer(length); if (crc != null) { crc.add_bits(allocation, length); crc.add_bits(channel2_allocation, length); } }
/// <summary> /// Generates frames for a broadcast transfer. /// </summary> /// <remarks> /// If the node is in passive mode, only single frame transfers will be allowed (they will be transmitted as anonymous). /// /// For anonymous transfers, maximum data type ID is limited to 3 (see specification for details). /// /// Pointer to the Transfer ID should point to a persistent variable and should be updated after every transmission. /// The Transfer ID value cannot be shared between transfers that have different descriptors. /// </remarks> public static IEnumerable <CanFrame> Broadcast( ulong dataTypeSignature, int dataTypeId, byte transferId, byte nodeId, UavcanPriority priority, byte[] payload, int payloadOffset, int payloadLen) { if (payload == null && payloadLen > 0) { throw new ArgumentException(nameof(payload)); } if (priority > UavcanPriority.Lowest) { throw new ArgumentException(nameof(priority)); } uint canId; ushort crc = Crc16.InitialValue; if (nodeId == 0) { if (payloadLen > 7) { throw new ArgumentException("Node ID expected.", nameof(nodeId)); } const ushort DTIDMask = (ushort)(1U << UavcanConstants.AnonymousMessageDataTypeIdBitLen) - 1; if ((dataTypeId & DTIDMask) != dataTypeId) { throw new ArgumentException(nameof(dataTypeId)); } // Anonymous transfer, random discriminator. ushort discriminator = (ushort)((Crc16.Add(Crc16.InitialValue, payload, payloadOffset, payloadLen)) & 0x7FFEU); canId = ((uint)priority << 24) | ((uint)discriminator << 9) | ((uint)(dataTypeId & DTIDMask) << 8) | nodeId; } else { canId = ((uint)priority << 24) | ((uint)dataTypeId << 8) | nodeId; if (payloadLen > 7) { crc = Crc16.AddSignature(crc, dataTypeSignature); crc = Crc16.Add(crc, payload, payloadOffset, payloadLen); } } return(CreateTxFrames(canId, transferId, crc, payload, payloadOffset, payloadLen)); }
public void Crc16_CrcWithModifiedPayloadComputesToNotZero(string input) { var bytes = input.ToBytes(); var crc = Crc16.ComputeChecksum(bytes); bytes[0] ^= 0x81; var payload = bytes.ConcatArray(BitConverter.GetBytes(crc)); var secondCrc = Crc16.ComputeChecksum(payload); secondCrc.Should().NotBe(0); }
public FlakeReader(AudioPCMConfig _pcm) { PCM = _pcm; crc8 = new Crc8(); crc16 = new Crc16(); Samples = new int[Flake.MAX_BLOCKSIZE * PCM.ChannelCount]; residualBuffer = new int[Flake.MAX_BLOCKSIZE * PCM.ChannelCount]; frame = new FlacFrame(PCM.ChannelCount); framereader = new BitReader(); }
/// <summary> /// 协议扩展,协议内容发送前调用 /// </summary> /// <param name="content">扩展前的原始协议内容</param> /// <returns>扩展后的协议内容</returns> public byte[] BytesExtend(byte[] content) { var crc = new byte[2]; //Modbus/Rtu协议扩张,增加CRC校验 var newFormat = new byte[content.Length + 2]; Crc16.GetInstance().GetCRC(content, ref crc); Array.Copy(content, 0, newFormat, 0, content.Length); Array.Copy(crc, 0, newFormat, newFormat.Length - 2, crc.Length); return(newFormat); }
public void Should_set_as_example() { foreach (var e in SamplesData.AllPackets) { var test = (byte[])e.Clone(); test[test.Length - 2] = 0; test[test.Length - 1] = 0; Crc16.SetCrc16(test); test.ShouldBe(e); } }
public void XModemCrcTest2() { byte[] data = new byte[7]; data[0] = 0xAB; data[1] = 0xCD; data[2] = 0xEF; data[3] = 0x12; data[4] = 0x34; data[5] = 0x56; data[6] = 0x78; Assert.AreEqual(0x948A, Crc16.XModemCrc(data, 0, 7)); }
/// <summary> /// Computes the hash. /// </summary> /// <param name="input">The input.</param> /// <returns></returns> public static ushort ComputeHash(string input) { if (input == null) { input = ""; } Crc16 crc = new Crc16(); byte[] bytes = Encoding.UTF8.GetBytes(input); return(crc.ComputeChecksum(bytes)); }
/// <summary> /// メッセージ送信 /// </summary> /// <param name="message"></param> /// <returns></returns> public bool SendMessage(string message, UInt16 seqNo) { bool ret = false; string packet; // シーケンス番号作成 string seqFormat = String.Format("D{0}", c_PacketSeqNoSize); string strSeqData = seqNo.ToString(seqFormat); // ボディ作成 byte[] msgData = Encoding.UTF8.GetBytes(message); // パケット長作成 string lenFormat = String.Format("D{0}", c_PacketLenSize); // パケット長CRC作成 int length = msgData.Length; string strLenCrc; string strLenData = length.ToString(lenFormat); byte[] crcData = Encoding.UTF8.GetBytes(strSeqData + strLenData); strLenCrc = Crc16.GetCrc(crcData, crcData.Length).ToString("X4"); // ボディCRC作成 string strBodyCrc; strBodyCrc = Crc16.GetCrc(msgData, msgData.Length).ToString("X4"); // パケット作成 packet = c_PacketHeader + strSeqData + strLenData + strLenCrc + message + strBodyCrc + c_PacketFooter; // 送信 try { if (this._udpClientSend != null && this._IsConnected == true) { byte[] data = Encoding.UTF8.GetBytes(packet); this._udpClientSend.Send(data, data.Length); ret = true; } } catch (Exception ex) { MoCsLog.WriteLog(String.Format(@"UDP送信異常({0}/{1})" , this.IpAddress , this.PortNo) + ":" + ex.Message); throw ex; } return(ret); }
/// <summary> /// * /// </summary> internal override void ReadAllocation(Bitstream stream, Header header, Crc16 crc) { int length = GetAllocationLength(header); Allocation = stream.GetBitsFromBuffer(length); Channel2Allocation = stream.GetBitsFromBuffer(length); if (crc != null) { crc.AddBits(Allocation, length); crc.AddBits(Channel2Allocation, length); } }
/// <summary> /// * /// </summary> internal override void ReadScaleFactorSelection(Bitstream stream, Crc16 crc) { if (Allocation != 0) { Scfsi = stream.GetBitsFromBuffer(2); Channel2Scfsi = stream.GetBitsFromBuffer(2); if (crc != null) { crc.AddBits(Scfsi, 2); crc.AddBits(Channel2Scfsi, 2); } } }
/// <summary> /// * /// </summary> public override void read_scalefactor_selection(Bitstream stream, Crc16 crc) { if (allocation != 0) { scfsi = stream.GetBitsFromBuffer(2); channel2_scfsi = stream.GetBitsFromBuffer(2); if (crc != null) { crc.add_bits(scfsi, 2); crc.add_bits(channel2_scfsi, 2); } } }
public void CombineTest16() { int lenAB = testBytes.Length; int lenA = 7; int lenB = lenAB - lenA; ushort crcAB = Crc16.ComputeChecksum(0, testBytes, 0, lenAB); ushort crcA = Crc16.ComputeChecksum(0, testBytes, 0, lenA); ushort crcB = Crc16.ComputeChecksum(0, testBytes, lenA, lenB); Assert.AreEqual <uint>(crcAB, Crc16.Combine(crcA, crcB, lenB), "CRC16 was not combined correctly."); Assert.AreEqual <uint>(crcB, Crc16.Combine(crcA, crcAB, lenB), "CRC16 was not substracted correctly."); Assert.AreEqual <uint>(crcA, Crc16.Substract(crcAB, crcB, lenB), "CRC16 was not substracted correctly."); }
private static bool _Run() { bool result = true; FCrc16 fcrc = new FCrc16(); Crc16 crc = new Crc16(); result = F.same <ushort>(fcrc.Table.AsEnumerable(), crc.Table.AsEnumerable(), (u1, u2) => u1 == u2); byte[] test = new byte[] { 0x45, 0x19, 0xA7, 0x00, 0xFE, 0xFF, 0x04, 0x4A }; ushort fChecksum = fcrc.ComputeChecksum(test); ushort cChecksum = crc.ComputeChecksum(test); result = result && (fChecksum == cChecksum); return(result); }
public byte[] Serialize() { var buf = new byte[FullPacketLength]; buf[0] = PacketLength; buf[1] = Address; buf[2] = (byte)Command; if (Data != null) { Array.Copy(Data, 0, buf, 3, DataLength); } Crc16.SetCrc16(buf, FullPacketLength); return(buf); }
internal byte[] BuildMessageFrame(IMODBUSMessage message) { List <byte> messageBody = new List <byte>(); messageBody.AddRange(message.MessageFrame); using (Crc16 Hash = new Crc16()) { Hash.Initialize(); messageBody.AddRange(Hash.ComputeHash(message.MessageFrame, 0, messageBody.Count)); } return(messageBody.ToArray()); }
internal bool ChecksumsMatch(IMessage message, byte[] messageFrame) { if (message.MessageFrame.Length < (messageFrame.Length - 2)) { return(false); } // Compute the hash using (Crc16 Hash = new Crc16()) { Hash.Initialize(); var crc = BitConverter.ToUInt16(Hash.ComputeHash(message.MessageFrame, 0, (messageFrame.Length - 2)), 0); return(BitConverter.ToUInt16(messageFrame, messageFrame.Length - 2) == crc); } }
public void TestCrc16(string name, ushort polynomial, ushort initialState, ushort xorOutput, bool reverseInput, bool reverseOutput, ushort check) { using (Crc16 crc = new Crc16(polynomial, initialState, xorOutput, reverseInput, reverseOutput)) { crc.Initialize(); var bytes = Encoding.UTF8.GetBytes(data); for (int i = 0; i < bytes.Length; i++) { crc.Append(bytes[i]); } ushort output = crc.CurrentOutput; Assert.AreEqual(check, output, 0); } }
void aprirePopupQrCodeInvioCassa() { InputBoxDialog d = new InputBoxDialog(); d.inputValue.Text = DateTime.Today.ToString("yyyy-MM-dd"); d.Title = "Inserire data riferimento (AAAA-MM-GG)"; bool?esito = d.ShowDialog(); if (esito != true) { return; } DateTime dataFinale = DateTime.ParseExact(d.inputValue.Text, "yyyy-MM-dd", CultureInfo.InvariantCulture); var chiusure = riempireDtoChiusure(dataFinale); if (chiusure == null) { dialogProvider.ShowMessage("Nessun dato estratto negli ultimi " + GIORNI_INDIETRO_CHIUSURE + " giorni", "Nessun dato"); return; } string messaggio = chiusure.serializeToPiccolaString(); // Aggiungo un crc di sicurezza Crc16 chk = new Crc16(); ushort crc16 = chk.ComputeChecksum(Encoding.ASCII.GetBytes(messaggio)); // aggiungo un prefisso che è un comando per telegram che vado ad implementare string qrCode = "/cc " + messaggio + "!" + crc16.ToString("X4"); string nomeFileTemp = Path.Combine(Path.GetTempPath(), "qrcode-cassa.ser.txt"); File.WriteAllBytes(nomeFileTemp, Encoding.ASCII.GetBytes(qrCode)); // Apro la popup lanciando un evento var ea = new OpenPopupRequestEventArgs { requestName = "QRcodeChiusureCassaPopup", param = qrCode }; RaisePopupDialogRequest(ea); if (ea.mioDialogResult == true) { } }
/// <summary> /// This is called by the framework to indicate a new operation. /// </summary> /// <param name="context"></param> protected override void Reset(BinarySerializationContext context) { if (_crc == null) { _crc = new Crc16(Polynomial, InitialValue) { IsDataReflected = IsDataReflected, IsRemainderReflected = IsRemainderReflected, FinalXor = FinalXor }; } _crc.Reset(); }
/// <summary> /// 协议扩展,协议内容发送前调用 /// </summary> /// <param name="content">扩展前的原始协议内容</param> /// <returns>扩展后的协议内容</returns> public byte[] BytesExtend(byte[] content) { //Modbus/Ascii协议扩张,前面增加:,后面增加LRC校验和尾字符 var newContent = new List <byte>(); newContent.AddRange(Encoding.ASCII.GetBytes(":")); foreach (var number in content) { newContent.AddRange(Encoding.ASCII.GetBytes(number.ToString("X2"))); } newContent.AddRange(Encoding.ASCII.GetBytes(Crc16.GetInstance().GetLRC(content))); newContent.Add(0x0d); newContent.Add(0x0a); return(newContent.ToArray()); }
public void ShouldComputeCrc16() { var crc16 = new Crc16(); // ISO/IEC13239: This should lead to the CRC 0x52ED byte[] source = { 0x02, 0x07, 0x01, 0x03, 0x01, 0x02, 0x00, 0x34, 0x07, 0x07, 0x1C, 0x59, 0x34, 0x6F, 0xE1, 0x83, 0x00, 0x00, 0x41, 0x06, 0x06, 0x7B, 0x3C, 0xFF, 0xCF, 0x3C, 0xC0 }; var hash1 = crc16.ComputeHash(source); Assert.AreEqual("52ED", BitConverter.ToString(hash1).Replace("-", "")); }
/// <summary> /// * /// </summary> internal override void ReadAllocation(Bitstream stream, Header header, Crc16 crc) { if ((Allocation = stream.GetBitsFromBuffer(4)) == 15) { } // cerr << "WARNING: stream contains an illegal allocation!\n"; // MPEG-stream is corrupted! crc?.AddBits(Allocation, 4); if (Allocation != 0) { Samplelength = Allocation + 1; Factor = TableFactor[Allocation]; Offset = TableOffset[Allocation]; } }
public ushort get_crc16() { if (have_bits_m == 0) { return(crc16_m); } ushort crc = 0; int n = have_bits_m >> 3; for (int i = 0; i < n; i++) { crc = (ushort)((crc << 8) ^ Crc16.table[(crc >> 8) ^ (byte)(cache_m >> (56 - (i << 3)))]); } return(Crc16.Substract(crc16_m, crc, n)); }
public static void SendUP(string text) { try { messagePos = 0; byte[] SYNC = new byte[] { 0xA5, 0x00 }; //Low endian byte[] TIME = GetMillisecondTime(); byte[] FID = GetFID(); byte[] XT = GetXT(); //Future will need it to take in an input byte[] CMD = GetCMD(text); byte[] DATA = GetData(); byte[] DATALEN = GetDataLen(DATA); //SYNC:2, TIME:4, FID:2, XT:4, CMD:2, LEN:2, DATA:0-65517, CRC:2 //bytes (8 bits) byte[] message = new byte[65535]; //18 for debug, 65535 for full AddToMessage(message, SYNC); AddToMessage(message, FID); AddToMessage(message, TIME); AddToMessage(message, XT); AddToMessage(message, CMD); AddToMessage(message, DATALEN); AddToMessage(message, DATA); var result = Crc16.ComputeChecksum(message); byte[] CRC = BitConverter.GetBytes(result); AddToMessage(message, CRC); //AsyncCamCom.SendNonAsync(message); incrementalCounter++; string s = ""; for (int i = 0; i < message.Length; i++) { if (i > 18 && i < 20) { s += "... "; i = message.Length - 2; } s += message[i].ToString("X") + " "; } //l_Send.Text = s; Console.WriteLine(s); } catch (Exception e) { Console.WriteLine("FAIL\n" + e.ToString()); } }
UInt16 tcpConnectionId(IPEndPoint src, IPEndPoint dst) { byte[] addr1 = src.Address.GetAddressBytes(); byte[] port1 = src.Port.GetBytes(); byte[] addr2 = dst.Address.GetAddressBytes(); byte[] port2 = dst.Port.GetBytes(); byte[] data = new byte[addr1.Length + port1.Length + addr2.Length + port2.Length]; addr1.CopyTo(data, 0); port1.CopyTo(data, addr1.Length); addr2.CopyTo(data, addr1.Length + port1.Length); port2.CopyTo(data, addr1.Length + port1.Length + addr2.Length); return(Crc16.ComputeChecksum(data)); }
static void Main(string[] args) { byte[] data = Encoding.ASCII.GetBytes("123456789"); var crc16 = new Crc16(Crc16.IBM, true); Console.WriteLine("CRC-16 = {0:X4}", crc16.Compute(data)); var crc16ccitt = new Crc16(Crc16.CCITT, false, 0xFFFF, 0); Console.WriteLine("CRC-16-CCITT = {0:X4}", crc16ccitt.Compute(data)); var crc32 = new Crc32(Crc32.IEEE, 0xFFFFFFFF, 0xFFFFFFFF); Console.WriteLine("CRC-32 = {0:X8}", crc32.Compute(data)); }
/// <summary> /// * /// </summary> public override void read_allocation(Bitstream stream, Header header, Crc16 crc) { if ((allocation = stream.GetBitsFromBuffer(4)) == 15) { } // cerr << "WARNING: stream contains an illegal allocation!\n"; // MPEG-stream is corrupted! if (crc != null) crc.add_bits(allocation, 4); if (allocation != 0) { samplelength = allocation + 1; factor = TableFactor[allocation]; offset = TableOffset[allocation]; } }
/// <summary> /// * /// </summary> public override void read_allocation(Bitstream stream, Header header, Crc16 crc) { allocation = stream.GetBitsFromBuffer(4); channel2_allocation = stream.GetBitsFromBuffer(4); if (crc != null) { crc.add_bits(allocation, 4); crc.add_bits(channel2_allocation, 4); } if (allocation != 0) { samplelength = allocation + 1; factor = TableFactor[allocation]; offset = TableOffset[allocation]; } if (channel2_allocation != 0) { channel2_samplelength = channel2_allocation + 1; channel2_factor = TableFactor[channel2_allocation]; channel2_offset = TableOffset[channel2_allocation]; } }
public abstract void ReadBitAllocation(Bitstream stream, Header header, Crc16 crc);
// new Crc16[1] to enable CRC checking. public LayerIDecoder() { crc = new Crc16(); }
public byte[] returnArrayBytesWithCRC16(byte[] inBytes) { Crc16 crc = new Crc16(Crc16Mode.CcittKermit); byte[] bytebegin = { DLE, STX }; byte[] byteend = { DLE, ETX }; byte[] tempb = returnWithOutDublicateETX(inBytes); var searchBegin = PatternAt(tempb, bytebegin); if (searchBegin == null) return null; var searchEnd = PatternAt(tempb, byteend); if (searchEnd == null) return null; var newArr = tempb.Skip((int)searchBegin + 2).Take((int)searchEnd - 2).ToArray(); byte[] a = new byte[newArr.Length + 1]; newArr.CopyTo(a, 0); a[newArr.Length] = ETX; //var control = tempb.Skip((int)searchEnd + 2).Take(2).ToArray(); byte[] crcBytes = crc.ComputeChecksumBytes(a); byte[] retBytes = new byte[inBytes.Length + 2]; inBytes.CopyTo(retBytes, 0); retBytes[retBytes.Length - 2] = crcBytes[0]; retBytes[retBytes.Length - 1] = crcBytes[1]; return retBytes; }
public abstract void read_allocation(Bitstream stream, Header header, Crc16 crc);
/// <summary> /// * /// </summary> public override void ReadBitAllocation(Bitstream stream, Header header, Crc16 crc) { base.ReadBitAllocation(stream, header, crc); }
/// <summary> /// returns CRC-16 of string as 4 hex characters /// </summary> private static string GetCrc16(string s) { if (String.IsNullOrEmpty(s)) return ""; byte[] b = new Crc16().ComputeChecksumBytes(Encoding.UTF8.GetBytes(s)); return b[0].ToString("x2") + b[1].ToString("x2"); }
/// <summary>Calculates the CRC-ModBus check-sum on specified portion of a buffer.</summary> /// <param name="data">Data buffer to perform check-sum on.</param> /// <param name="startIndex">Starts index in data buffer to begin check-sum.</param> /// <param name="length">Total number of bytes from <paramref name="startIndex">startIndex</paramref> to /// perform check-sum over.</param> /// <returns>Computed CRC-ModBus checksum over the specified portion of the buffer.</returns> public static ushort ModBusCrcChecksum(this byte[] data, int startIndex, int length) { Crc16 checksum = new Crc16(ChecksumType.ModBus); checksum.Update(data, startIndex, length); return checksum.Value; }
/// <summary> /// * /// </summary> public override void read_allocation(Bitstream stream, Header header, Crc16 crc) { base.read_allocation(stream, header, crc); }
public FlakeReader(AudioPCMConfig _pcm) { pcm = _pcm; crc8 = new Crc8(); crc16 = new Crc16(); samplesBuffer = new int[Flake.MAX_BLOCKSIZE * PCM.ChannelCount]; residualBuffer = new int[Flake.MAX_BLOCKSIZE * PCM.ChannelCount]; frame = new FlacFrame(PCM.ChannelCount); framereader = new BitReader(); }
/// <summary> /// * /// </summary> public virtual void read_scalefactor_selection(Bitstream stream, Crc16 crc) { if (allocation != 0) { scfsi = stream.GetBitsFromBuffer(2); if (crc != null) crc.add_bits(scfsi, 2); } }
private static ushort ComputeCrc(byte[] val) { var crc16 = new Crc16(Crc16Mode.Standard); return crc16.ComputeChecksum(val); }