public static void AddAnimHash(string name, ref Dictionary <uint, string> dict) { uint crc = Crc32.Compute(name.ToLower()); if (dict.ContainsValue(name) || dict.ContainsKey(crc)) { return; } dict.Add(crc, name); }
static void CheckCrc(int crc, ReusableMemoryStream stream, long crcStartPos) { var computedCrc = (int)Crc32.Compute(stream, crcStartPos, stream.Position - crcStartPos); if (computedCrc != crc) { throw new CrcException( string.Format("Corrupt message: CRC32 does not match. Calculated {0} but got {1}", computedCrc, crc)); } }
private static void CheckChecksum(IByteBuffer buffer, int length) { buffer.ResetReaderIndex(); var checksumData = buffer.ToArray(length); var checksum = buffer.ReadUnsignedIntLE(); var computeChecksum = Crc32.Compute(checksumData); Guard.That(computeChecksum).IsEqual(checksum); }
/// <summary> /// Sets (and returns) a valid CRC on a GameMessage for UDP /// </summary> /// <param name="Message"></param> /// <returns></returns> public ushort CreatePacketCRCUDP(GameMessage Message) { // create a generic CRC32 of message body uint crc32 = Crc32.Compute(Message.BodyBytes); // no scrambling on UDP // set encoded and shortened CRC on message Message.Header.HeaderCRC = (ushort)crc32; return(Message.Header.HeaderCRC); }
private static int FinishPacket(Span <byte> buffer, int offset) { // Payload length BinaryPrimitives.WriteUInt16BigEndian(buffer.Slice(2), (ushort)(offset - 4)); // calculate crc and insert at the end of the message var crc = Crc32.Compute(buffer.Slice(0, offset)); BinaryPrimitives.WriteUInt32LittleEndian(buffer.Slice(offset), crc); return(offset + 4); }
void _send_config(uint prev_crc) { // Build config commands foreach (var cb in this._config_callbacks) { cb(); } this._add_custom(); this._config_cmds.Insert(0, $"allocate_oids count={this._oid_count}"); // Resolve pin names var mcu_type = this._serial.msgparser.get_constant("MCU"); var pin_resolver = new PinResolver(mcu_type); if (this._pin_map != null) { pin_resolver.Update_aliases(this._pin_map); } for (int i = 0; i < _config_cmds.Count; i++) { this._config_cmds[i] = pin_resolver.Update_command(this._config_cmds[i]); } for (int i = 0; i < _init_cmds.Count; i++) { this._init_cmds[i] = pin_resolver.Update_command(this._init_cmds[i]); } // Calculate config CRC var bytes = Encoding.ASCII.GetBytes(string.Join('\n', this._config_cmds)); var config_crc = Crc32.Compute(bytes) & 0xffffffff; System.IO.File.WriteAllText("config.txt", string.Join('\n', this._config_cmds) + "\n" + config_crc); logging.Debug($"Config send crc32 {config_crc}"); this.add_config_cmd($"finalize_config crc={config_crc}"); // Transmit config messages (if needed) if (prev_crc == 0) { logging.Info("Sending MCU '{0}' printer configuration...", this._name); foreach (var c in this._config_cmds) { this._serial.send(c); } } else if (config_crc != prev_crc) { this._check_restart("CRC mismatch"); throw new McuException($"MCU '{this._name}' CRC does not match config"); } // Transmit init messages foreach (var c in this._init_cmds) { this._serial.send(c); } }
public Dictionary <uint, string> getAnimNames(string path) { Dictionary <uint, string> hashpairs = new Dictionary <uint, string>(); if (path.EndsWith(".pac")) { byte[] filebytes = File.ReadAllBytes(path); int count = (int)Util.GetWord(filebytes, 8, Runtime.WorkingEndian); for (int i = 0; i < count; i++) { uint off = (uint)Util.GetWord(filebytes, 0x10 + (i * 4), Runtime.WorkingEndian); string FileName = Util.GetString(filebytes, off, Runtime.WorkingEndian); string AnimName = Regex.Match(FileName, @"(.*)([A-Z])([0-9][0-9])(.*)\.omo").Groups[4].ToString(); hashpairs.Add(Crc32.Compute(Encoding.ASCII.GetBytes(AnimName.ToLower())), AnimName); hashpairs.Add(Crc32.Compute(Encoding.ASCII.GetBytes((AnimName + "_C2").ToLower())), AnimName + "_C2"); hashpairs.Add(Crc32.Compute(Encoding.ASCII.GetBytes((AnimName + "_C3").ToLower())), AnimName + "_C3"); if (AnimName.EndsWith("s4s", StringComparison.InvariantCultureIgnoreCase) || AnimName.EndsWith("s3s", StringComparison.InvariantCultureIgnoreCase)) { hashpairs.Add(Crc32.Compute(Encoding.ASCII.GetBytes(AnimName.Substring(0, AnimName.Length - 1).ToLower())), AnimName.Substring(0, AnimName.Length - 1)); } } } else if (path.EndsWith(".bch")) { DataSource src = new DataSource(FileMap.FromFile(path)); int off = *(int *)(src.Address + 0x0C); VoidPtr addr = src.Address + off; while (*(byte *)addr != 0) { string s = new string((sbyte *)addr); string AnimName = Regex.Match(s, @"(.*)([A-Z])([0-9][0-9])(.*)").Groups[4].ToString(); if (AnimName != "") { hashpairs.Add(Crc32.Compute(Encoding.ASCII.GetBytes(AnimName.ToLower())), AnimName); hashpairs.Add(Crc32.Compute(Encoding.ASCII.GetBytes((AnimName + "_C2").ToLower())), AnimName + "_C2"); hashpairs.Add(Crc32.Compute(Encoding.ASCII.GetBytes((AnimName + "_C3").ToLower())), AnimName + "_C3"); if (AnimName.EndsWith("s4s", StringComparison.InvariantCultureIgnoreCase) || AnimName.EndsWith("s3s", StringComparison.InvariantCultureIgnoreCase)) { hashpairs.Add(Crc32.Compute(Encoding.ASCII.GetBytes(AnimName.Substring(0, AnimName.Length - 1).ToLower())), AnimName.Substring(0, AnimName.Length - 1)); } } addr += s.Length + 1; } } return(hashpairs); }
private void treeView_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e) { TreeNode node = e.Node; if (node != null && node.Parent != null && node.SelectedImageKey != UIConstants.ICON_FOLDER && node.SelectedImageKey != UIConstants.ICON_PACKED) { string absolutePath = node.Name; if (string.IsNullOrEmpty(absolutePath)) { return; } //Extract string fullExtractedFile = _ProjectManager.ExtractResource(absolutePath); uint crcFile = Crc32.Compute(File.ReadAllBytes(fullExtractedFile)); //Plugin ResourceSelected hooks bool pluginUsed = false; string relativePath = _ProjectManager.GetRelativePath(absolutePath); ResourceCollection resCol = GetFirstLevelNode(node).Tag as ResourceCollection; foreach (Sm4shBasePlugin plugin in _ProjectManager.Plugins) { if (plugin.InternalResourceSelected(resCol, relativePath, fullExtractedFile)) { pluginUsed = true; break; } } //If no plugin used, try hexeditor if (!pluginUsed) { if (string.IsNullOrEmpty(_ProjectManager.CurrentProject.ProjectHexEditorFile)) { LogHelper.Info(UIStrings.INFO_FILE_HEX); return; } Process process = Process.Start(_ProjectManager.CurrentProject.ProjectHexEditorFile, "\"" + fullExtractedFile + "\""); process.WaitForExit(); } //Check extract file, if changed, ask to add in workspace uint compareCrcFile = Crc32.Compute(File.ReadAllBytes(fullExtractedFile)); if (crcFile != compareCrcFile) { if (MessageBox.Show(string.Format(UIStrings.INFO_FILE_MODIFIED, absolutePath), UIStrings.CAPTION_FILE_MODIFIED, MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes) { AddOrReplaceFiles(treeView.SelectedNode.Parent, new string[] { fullExtractedFile }); } } } }
public static byte[] Serialize(this TLSEnvelope tlsEnvelope) { if (tlsEnvelope.TotalLength != TLSEnvelope.HeaderLength + tlsEnvelope.EncipheredPayload.Length) { throw new InvalidOperationException("Actual payload lenght does not match Length field."); } int serializedLength = TLSEnvelope.HeaderLength + tlsEnvelope.EncipheredPayload.Length; var serialized = new byte[serializedLength]; serialized[0] = TLSEnvelope.Version; serialized[1] = TLSEnvelope.MessageType; byte[] lenghtBytes = BitConverter.GetBytes(serializedLength); serialized[2] = lenghtBytes[0]; serialized[3] = lenghtBytes[1]; serialized[4] = lenghtBytes[2]; serialized[5] = lenghtBytes[3]; byte[] keyHint = BitConverter.GetBytes(tlsEnvelope.PrivateKeyHint); serialized[6 + 4] = keyHint[0]; serialized[7 + 4] = keyHint[1]; serialized[8 + 4] = keyHint[2]; serialized[9 + 4] = keyHint[3]; serialized[10 + 4] = keyHint[4]; serialized[11 + 4] = keyHint[5]; serialized[12 + 4] = keyHint[6]; serialized[13 + 4] = keyHint[7]; byte[] dynamicPublicKeyId = BitConverter.GetBytes(tlsEnvelope.DynamicPublicKeyId); serialized[14 + 4] = dynamicPublicKeyId[0]; serialized[15 + 4] = dynamicPublicKeyId[1]; serialized[16 + 4] = dynamicPublicKeyId[2]; serialized[17 + 4] = dynamicPublicKeyId[3]; serialized[18 + 4] = dynamicPublicKeyId[4]; serialized[19 + 4] = dynamicPublicKeyId[5]; serialized[20 + 4] = dynamicPublicKeyId[6]; serialized[21 + 4] = dynamicPublicKeyId[7]; Buffer.BlockCopy(tlsEnvelope.DynamicPublicKey, 0, serialized, 22 + 4, 32); Buffer.BlockCopy(tlsEnvelope.EncipheredPayload, 0, serialized, TLSEnvelope.HeaderLength, tlsEnvelope.EncipheredPayload.Length); var crc32 = Crc32.Compute(serialized); byte[] crc32Bytes = BitConverter.GetBytes(crc32); serialized[6] = crc32Bytes[0]; serialized[7] = crc32Bytes[1]; serialized[8] = crc32Bytes[2]; serialized[9] = crc32Bytes[3]; return(serialized); }
//N.B., MessageSets are not preceded by an int32 like other array elements in the protocol. // //MessageSet => [Offset MessageSize Message] // Offset => int64 // MessageSize => int32 // //Message => Crc MagicByte Attributes Key Value // Crc => int32 // MagicByte => int8 // Attributes => int8 // Key => bytes // Value => bytes private static IEnumerable <Message> ReadMessageSet(MemoryStream stream) { // "As an optimization the server is allowed to return a partial message at the end of the message set. // Clients should handle this case" var messageSetSize = BigEndianConverter.ReadInt32(stream); var remainingMessageSetBytes = messageSetSize; while (remainingMessageSetBytes > 0) { // we need at least be able to read offset and messageSize if (remainingMessageSetBytes < +8 + 4) { // not enough bytes left. This is a partial message. Skip to the end of the message set. stream.Position += remainingMessageSetBytes; yield break; } var offset = BigEndianConverter.ReadInt64(stream); var messageSize = BigEndianConverter.ReadInt32(stream); // we took 12 bytes there, check again that we have a full message. remainingMessageSetBytes -= 8 + 4; if (remainingMessageSetBytes < messageSize) { // not enough bytes left. This is a partial message. Skip to the end of the message set. stream.Position += remainingMessageSetBytes; yield break; } // Message var crc = BigEndianConverter.ReadInt32(stream); var crcPos = stream.Position; var magic = stream.ReadByte(); var attributes = stream.ReadByte(); var msg = new Message(); msg.Key = ReadByteArray(stream); msg.Value = ReadByteArray(stream); msg.Offset = offset; var pos = stream.Position; var computedCrcArray = Crc32.Compute(stream, crcPos, pos - crcPos); var computedCrc = BigEndianConverter.ToInt32(computedCrcArray); if (computedCrc != crc) { throw new BrokerException(string.Format("Corrupt message: Crc does not match. Caclulated {0} but got {1}", computedCrc, crc)); } yield return(msg); // subtract messageSize of that message from remaining bytes remainingMessageSetBytes -= messageSize; } }
public UInt32 CalculateCRC(Stream stream) { var originalPos = stream.Position; var headerSize = HeaderSize + Magic.MagicSize; stream.Seek(headerSize, SeekOrigin.Begin); byte[] body = new byte[fileSize - headerSize]; stream.Read(body, 0, (int)(fileSize - headerSize)); UInt32 crc = Crc32.Compute(body); stream.Seek(originalPos, SeekOrigin.Begin); return(crc); }
public void Crc32NoRemainderReflectTest() { var crc = new Crc32(Crc32Polynomial, 0xffffffff) { IsRemainderReflected = false }; var messageData = System.Text.Encoding.ASCII.GetBytes("hello world"); crc.Compute(messageData, 0, messageData.Length); var final = crc.ComputeFinal(); Assert.AreEqual(0x923588bf, final); }
private void hashMatch_Click(object sender, EventArgs e) { foreach (Bone bone in VBN.bones) { uint bi = 0; MainForm.Hashes.names.TryGetValue(bone.Text, out bi); bone.boneId = bi; if (bone.boneId == 0) { bone.boneId = Crc32.Compute(bone.Text); } } }
/// <summary> /// Computes the crc32. /// </summary> /// <returns>The crc32.</returns> /// <param name="path">Path.</param> public static uint ComputeCrc32(string path) { if (File.Exists(path)) { var bytes = File.ReadAllBytes(path); uint crc = Crc32.Compute(bytes); return(crc); } else { return(0); } }
public override Stream OpenEntry(ArcFile arc, Entry entry) { var azarc = arc as AsbArchive; if (null == azarc || entry.Size < 20 || !arc.File.View.AsciiEqual(entry.Offset, "ASB\x1a")) { return(arc.File.CreateStream(entry.Offset, entry.Size)); } uint packed = arc.File.View.ReadUInt32(entry.Offset + 4); uint unpacked = arc.File.View.ReadUInt32(entry.Offset + 8); if (12 + packed != entry.Size) { return(arc.File.CreateStream(entry.Offset, entry.Size)); } uint key = azarc.Key ^ unpacked; key ^= ((key << 12) | key) << 11; uint first = arc.File.View.ReadUInt16(entry.Offset + 16); first = (first - key) & 0xffff; if (first != 0xda78) // doesn't look like zlib stream { return(arc.File.CreateStream(entry.Offset, entry.Size)); } var input = arc.File.View.ReadBytes(entry.Offset + 12, packed); unsafe { fixed(byte *raw = input) { uint *encoded = (uint *)raw; for (int i = 0; i < input.Length / 4; ++i) { encoded[i] -= key; } } } // first 4 bytes are CRC32 of the compressed stream uint checksum = LittleEndian.ToUInt32(input, 0); if (checksum != Crc32.Compute(input, 4, input.Length - 4)) { return(arc.File.CreateStream(entry.Offset, entry.Size)); } return(new ZLibStream(new MemoryStream(input, 4, input.Length - 4), CompressionMode.Decompress)); }
public override ArcFile TryOpen(ArcView file) { int ext_count = file.View.ReadInt32(4); int count = file.View.ReadInt32(8); uint index_length = file.View.ReadUInt32(12); if (ext_count < 1 || ext_count > 8 || count <= 0 || count > 0xfffff || index_length <= 0x14 || index_length >= file.MaxOffset) { return(null); } var packed_index = file.View.ReadBytes(0x30, index_length); if (packed_index.Length != index_length) { return(null); } uint base_offset = 0x30 + index_length; uint crc = LittleEndian.ToUInt32(packed_index, 0); if (crc != Crc32.Compute(packed_index, 0x14, packed_index.Length - 0x14)) { throw new InvalidFormatException("CRC32 mismatch"); } var reader = new IndexReader(packed_index, count); var index = reader.Unpack(); int index_offset = 0; var dir = new List <Entry> (count); for (int i = 0; i < count; ++i) { var name = Binary.GetCString(index, index_offset + 0x10, 0x30); if (name.Length > 0) { var entry = FormatCatalog.Instance.Create <Entry> (name); entry.Offset = base_offset + LittleEndian.ToUInt32(index, index_offset); entry.Size = LittleEndian.ToUInt32(index, index_offset + 4); if (entry.CheckPlacement(file.MaxOffset)) { dir.Add(entry); } } index_offset += 0x40; } if (0 == dir.Count) { return(null); } return(new ArcFile(file, this, dir)); }
public void ComputeTest() { using (Crc32 crc32 = new Crc32()) { foreach (Tuple <string, UInt32?> t in tests) { byte[] data = Encoding.ASCII.GetBytes(t.Item1); var value = crc32.Compute(data, 0, data.Length); Assert.AreEqual(t.Item2, value); } } }
public override long SaveFileData(Stream output, bool compress, IProgressContext progress = null) { Entry.offset = (int)output.Position; Entry.chunkIndex = 0; if (!ContentChanged) { Entry.chunkCount = Chunks.Count; FileData.Position = 0; FileData.CopyTo(output); ContentChanged = false; return(FileData.Length); } Entry.chunkCount = 1; Entry.decompSize = (int)FileData.Length; FileData.Position = 0; Entry.crc32 = BinaryPrimitives.ReadUInt32BigEndian(Crc32.Compute(FileData)); var finalStream = FileData; if (_chunkStream.UsesCompression) { FileData.Position = 0; finalStream = new MemoryStream(); Kompression.Implementations.Compressions.TaikoLz80.Build().Compress(FileData, finalStream); } Entry.compSize = (int)finalStream.Length; finalStream.Position = 0; finalStream.CopyTo(output); var compFlag = _chunkStream.UsesCompression ? 0x80000000 : 0; Chunks = new[] { new L7cChunkEntry { chunkSize = (int)(compFlag | ((uint)finalStream.Length & 0xFFFFFF)) } }; ContentChanged = false; return(finalStream.Length); }
private void SaveHandler(LNReq_Save msg, PBChannel channel, int handle, uint seq) { if (!Enable) { LogSys.Log(LOG_TYPE.ERROR, "Save a message while DataOperator is Disable"); return; } var reply = NLRep_Save.CreateBuilder(); reply.SetDsMsgId(msg.DsMsgId); reply.SetKey(msg.Key); reply.Result = NLRep_Save.Types.SaveResult.Success; try { byte[] data_bytes = ByteString.Unsafe.GetBuffer(msg.DsBytes); int calc_checksum = Crc32.Compute(data_bytes); if (msg.Checksum != calc_checksum) { throw new DataChecksumError(msg.Checksum, calc_checksum); } string dataTypeName = string.Empty; if (m_DSDMessages.TryGetValue(msg.DsMsgId, out dataTypeName)) { DataCacheSystem.Instance.QueueAction(DataCacheSystem.Instance.DirectSave, msg.DsMsgId, msg.Key, data_bytes); } else { dataTypeName = MessageMapping.Query(msg.DsMsgId).Name; if (dataTypeName.StartsWith("DSD_")) { //直接写入数据库 m_DSDMessages.AddOrUpdate(msg.DsMsgId, dataTypeName, (key, oldValue) => dataTypeName); DataCacheSystem.Instance.QueueAction(DataCacheSystem.Instance.DirectSave, msg.DsMsgId, msg.Key, data_bytes); } else { //写入数据缓存 DataCacheSystem.Instance.SaveActionQueue.QueueAction(DataCacheSystem.Instance.Save, msg.DsMsgId, msg.Key, data_bytes); } } } catch (Exception e) { reply.Result = NLRep_Save.Types.SaveResult.Error; reply.SetError(e.Message); LogSys.Log(LOG_TYPE.ERROR, "Save data ERROR: msgId:({0}) seq:({1}) error:({2}) detail:{3}", msg.DsMsgId, seq, e.Message, e.StackTrace); } channel.Send(reply.Build()); }
public PackagedFileInfo WriteFile(FileInfo info) { // Assume that all files are written uncompressed (worst-case) when calculating package sizes var size = info.Size(); if (streams.Last().Position + size > MaxPackageSize) { // Start a new package file if the current one is full. var partPath = Package.MakePartFilename(path, streams.Count); var nextPart = new FileStream(partPath, FileMode.Create, FileAccess.Write); streams.Add(nextPart); } var stream = streams.Last(); var packaged = new PackagedFileInfo(); packaged.PackageStream = stream; packaged.Name = info.Name; packaged.UncompressedSize = size; packaged.ArchivePart = (UInt32)(streams.Count - 1); packaged.OffsetInFile = (UInt32)stream.Position; packaged.Flags = BinUtils.MakeCompressionFlags(Compression, CompressionLevel); var reader = info.MakeReader(); var uncompressed = reader.ReadBytes((int)reader.BaseStream.Length); var compressed = BinUtils.Compress(uncompressed, Compression, CompressionLevel); stream.Write(compressed, 0, compressed.Length); reader.Dispose(); packaged.SizeOnDisk = (UInt32)(stream.Position - packaged.OffsetInFile); packaged.Crc = Crc32.Compute(compressed); var padLength = PaddingLength(); if (stream.Position % padLength > 0) { // Pad the file to a multiple of 64 bytes byte[] pad = new byte[padLength - (stream.Position % padLength)]; for (int i = 0; i < pad.Length; i++) { pad[i] = 0xAD; } stream.Write(pad, 0, pad.Length); } return(packaged); }
public bool ValidateCrc() { if (QuickAndDirtyMode) { return(true); } var original = CrcHash; CrcHash = 0; var actual = Crc32.Compute(_data); CrcHash = original; return(actual == original); }
private SendData PreparePackage(ref byte[] pData) { if (PublicServerRsaKey != null) { pData = PublicServerRsaKey.Encrypt(pData, true); } int pPackageSeq = pPackageSeqNum++; byte[] pReadyPackage = new byte[pData.Length + 12]; Helper.SetData(ref pReadyPackage, BitConverter.GetBytes(pData.Length + 12), 0); // length Helper.SetData(ref pReadyPackage, BitConverter.GetBytes(pPackageSeq), 4); // sequence num. starting at 0 Helper.SetData(ref pReadyPackage, pData, 8); // actual data Helper.SetData(ref pReadyPackage, BitConverter.GetBytes(Crc32.Compute(Helper.GetData(pReadyPackage, 0, pReadyPackage.Length - 4))), pData.Length + 8); // crc32 of the whole package, with len & seq. num. pData = pReadyPackage; return(new SendData(pData, pPackageSeq)); }
public void BadVersionIfCrcOkButStreamFlagUnknown() { var bytes = Compressed.Clone() as byte[]; byte[] streamFlags = { 0x00, 0xF4 }; byte[] crc = Crc32.Compute(streamFlags).ToLittleEndianBytes(); streamFlags.CopyTo(bytes, 6); crc.CopyTo(bytes, 8); using (Stream badFlagStream = new MemoryStream(bytes)) { BinaryReader br = new BinaryReader(badFlagStream); var header = new XZHeader(br); var ex = Assert.Throws <InvalidDataException>(() => { header.Process(); }); Assert.Equal("Unknown XZ Stream Version", ex.Message); } }
private void WriteCrc(int offset) { uint crc; ArraySegment <byte> segment; var computeFrom = offset + Request.IntegerByteSize; if (!_stream.TryGetBuffer(out segment)) { // the stream is a memorystream, always owning its own buffer throw new NotSupportedException(); } crc = Crc32.Compute(segment.Skip(computeFrom)); _stream.Position = offset; Write(crc); }
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)); }
private static void CheckHash(string hashStr) { uint hash = Crc32.Compute(hashStr); if (!hashes.ContainsKey(hash)) { hashes.Add(hash, hashStr); } uint mmhash = MurMurHash3.Hash(hashStr); if (!mmhashes.ContainsKey(mmhash)) { mmhashes.Add(mmhash, hashStr); } }
public int sceZlibDecompress(byte *OutBuffer, int OutBufferLength, byte *InBuffer, uint *Crc32Addr) { var InStream = new PointerStream(InBuffer); var OutStream = new PointerStream(OutBuffer, OutBufferLength); _Decompress(InStream, OutStream); var OutLength = (int)OutStream.Position; if (Crc32Addr != null) { *Crc32Addr = Crc32.Compute(PointerUtils.PointerToByteArray(OutBuffer, OutLength)); } return(OutLength); }
private static void WriteIHDRChunk(Span <byte> png, int width, int height) { // https://en.wikipedia.org/wiki/Portable_Network_Graphics#Critical_chunks // http://www.libpng.org/pub/png/spec/1.2/PNG-Chunks.html // because we know the length and name of this chunk ahead of time, we can write it immediately // v hex for '13' // v ASCII chars "IHDR" const int chunkLength = 13; const ulong chunkHeader = 0x0000000D_49484452; const int chunkHeaderSize = sizeof(ulong); // 4 byte big endian width var couldWriteHeader = BinaryPrimitives.TryWriteUInt64BigEndian(png, chunkHeader); Debug.Assert(couldWriteHeader); // 4 byte big endian height const int widthSize = sizeof(int); var couldWriteWidth = BinaryPrimitives.TryWriteInt32BigEndian(png.Slice(chunkHeaderSize, 4), width); Debug.Assert(couldWriteWidth); const int heightSize = sizeof(int); var couldWriteHeight = BinaryPrimitives.TryWriteInt32BigEndian(png.Slice(chunkHeaderSize + widthSize, 4), height); Debug.Assert(couldWriteHeight); // write 5 bytes (3 extra overflow, but it's safe in our case) // 0x08 - bit depth of 8 // 0x06 - color type: 6 (Each pixel is an R,G,B triple, followed by an alpha sample.) // 0x00 - deflate compression method // 0x00 - filter type 'none' - do no extra processing on our side lol // 0x00 - no interlacing/progressive loading // the remaining 3 bytes are padding const int configurationSize = 5; var slice = png.Slice(chunkHeaderSize + widthSize + heightSize, sizeof(ulong)); var couldWriteConfiguration = BinaryPrimitives.TryWriteUInt64BigEndian(slice, 0x0806000000_000000); Debug.Assert(couldWriteConfiguration); var crc32 = Crc32.Compute(png.Slice(sizeof(uint), 4 + chunkLength)); var crcTarget = png.Slice(chunkHeaderSize + widthSize + heightSize + configurationSize, 4); var couldWriteCrc32 = BinaryPrimitives.TryWriteUInt32BigEndian(crcTarget, crc32); Debug.Assert(couldWriteCrc32); }
private void btnSave_Click(object sender, EventArgs e) { if (IO == null) { MessageBox.Show("No file open!"); } else { IO.Offset = 4; byte[] buffer = IO.ReadBytes(0x20EB14); uint crc = Crc32.Compute(buffer); IO.Offset = 0; txtComputed.Text = crc.ToString("X4"); IO.Close(); MessageBox.Show("Saved!"); } }
/// <summary> /// tính crc với mục đích kiểm tra sự đồng bộ hóa /// </summary> private UInt32 ComputeCRC() { OutputMemoryBitStream output = new OutputMemoryBitStream(); foreach (var pair in mNetworkIdToGameobjectDic) { NetworkObject mObject = pair.Value.GetComponent <NetworkObject>(); if (mObject != null) { mObject.WriteForCrc(ref output); } } UInt32 re = Crc32.Compute(output.GetBuffer(), 0, output.GetByteLength()); return(re); }