コード例 #1
0
 static uint CalculateDigest(byte[] data, uint offset, uint size)
 {
     CRC crc = new CRC();
     // crc.Init();
     crc.Update(data, offset, size);
     return crc.GetDigest();
 }
コード例 #2
0
ファイル: ParteKamaleon.cs プロジェクト: albfernandez/dalle
 public ParteKamaleon()
 {
     nombre = "kamaleon1";
     descripcion = "KamaleoN v 1.0";
     web = "http://www.kamaleonsoft.com";
     parteFicheros = false;
     compatible = false;
     crc = new NullCRC();
 }
コード例 #3
0
ファイル: Common.cs プロジェクト: xorex/game-patcher
        public static string GetHash(string Name)
        {
            if (Name == string.Empty)
            {
                return(string.Empty);
            }

            CRC crc = new CRC();

            string Hash = string.Empty;

            using (FileStream fileStream = File.Open(Name, FileMode.Open))
            {
                foreach (byte b in crc.ComputeHash(fileStream))
                {
                    Hash += b.ToString("x2").ToLower();
                }
            }

            return(Hash);
        }
コード例 #4
0
        public AnalysisDataModel AnalysisData(string Data)
        {
            AnalysisDataModel model      = new AnalysisDataModel();
            TimeFormatHelper  timeHelper = new TimeFormatHelper();
            string            data1      = Data.Substring(0, 55);
            string            crc        = Data.Substring(55, 4);

            if (CRC.ToModbusCRC16(data1) == crc)
            {
                model.Data0  = data1.Substring(0, 11);                          //电话号码
                model.Data1  = MathHelper.HexToDouble(data1.Substring(11, 16)); //瞬时流量
                model.Data2  = MathHelper.HexToDouble(data1.Substring(27, 16));
                model.Data3  = data1.Substring(43, 12);
                model.Result = AnalysisDataModel.AnalysisResult.OK;
            }
            else
            {
                model.Result = AnalysisDataModel.AnalysisResult.ERR;
            }
            return(model);
        }
コード例 #5
0
        private void SocketServer_NewMessage2Event(System.Net.IPEndPoint remoteIpEndPoint, string Message)
        {
            SimpleLogHelper.Instance.WriteLog(LogType.Info, Message);
            SimpleLogHelper.Instance.WriteLog(LogType.Info, Message.Length);
            //验证
            string          commandText = "SELECT TOP 1 [正累积流量] AS 'Water' FROM Water ORDER BY [更新时间] DESC";
            List <TSKModel> models      = sql.GetDataTable <TSKModel>(commandText);

            if (models != null)
            {
                string a = MathHelper.SingleToHex(models[0].Water);
                Debug.WriteLine(a);
                string backdata = Message.Substring(0, 4);
                backdata += MathHelper.DecToHex((int.Parse(Message.Substring(10, 2)) * 2)
                                                .ToString()).PadLeft(2, '0');
                backdata += a;
                backdata += CRC.ToModbusCRC16(backdata);
                SimpleLogHelper.Instance.WriteLog(LogType.Info, "返回的数据是:" + backdata);
                socketServer.Send(remoteIpEndPoint, MathHelper.StrToHexByte(backdata));
            }
        }
        public bool test_CRC(byte[] data_with_generated_crc, CRC.Setting settings)
        {
            bool errors = false;

            CRC.Setting set = settings;

            CRC test_CRC = new CRC(set);

            byte[] test_score = test_CRC.ComputeHash(data_with_generated_crc);

            for (int i = 0; i < test_score.Length; i++)
            {
                if (test_score[i] != 0)
                {
                    errors = true;
                    return(errors);
                }
            }

            return(errors);
        }
コード例 #7
0
        public override bool isValid()
        {
            bool valid = true;

            for (int x = 0; x < mCRC.Length; x++)
            {
                CRC crc = mCRC[x];

                if (crc != null)
                {
                    if (crc == CRC.FAILED_CRC ||
                        crc == CRC.FAILED_PARITY ||
                        crc == CRC.UNKNOWN)
                    {
                        valid = false;
                    }
                }
            }

            return(valid);
        }
コード例 #8
0
        void MaybeGetHeader(List <VHDX_HEADER> headerList, int offset)
        {
            var bytes = mHdd.ReadBytes(offset, 4096);

            if (Program.ToStruct <UInt32>(bytes, 0) != HEADER_SIG)
            {
                return;
            }
            UInt32 checksum = Program.ToStruct <UInt32>(bytes, 4);

            for (int i = 0; i < 4; i++)
            {
                bytes[i + 4] = 0;
            }
            if (checksum != CRC.Compute(bytes))
            {
                return;
            }

            headerList.Add(Program.ToStruct <VHDX_HEADER>(bytes));
        }
コード例 #9
0
ファイル: Program.cs プロジェクト: shawlucas/MasterOcarina
        private static void SetCRC(string[] args)
        {
            string inRom;

            if (args.Length != 1)
            {
                return;
            }

            inRom = args[0];

            if (!FileExists(inRom))
            {
                return;
            }

            using (FileStream fs = new FileStream(inRom, FileMode.Open))
            {
                CRC.Write(fs);
            }
        }
コード例 #10
0
 protected override void Dispose(bool disposing)
 {
     if (this.mCurrentCRC != this.mExpectedCRC)
     {
         throw new InvalidOperationException();
     }
     try
     {
         if (disposing && !this.mClosed)
         {
             this.mClosed     = true;
             this.mCurrentCRC = CRC.Finish(this.mCurrentCRC);
             if (this.mCurrentCRC == this.mExpectedCRC)
             {
                 Debug.WriteLine("CRC ok: " + this.mExpectedCRC.ToString("x8"));
             }
             else
             {
                 Debugger.Break();
                 Debug.WriteLine("bad CRC");
             }
             double num  = 1.0 / ((double)this.mLength);
             double num2 = 0.0;
             for (int i = 0; i < 0x100; i++)
             {
                 if (this.mBytes[i] != 0L)
                 {
                     double a = num * this.mBytes[i];
                     num2 -= a * Math.Log(a, 256.0);
                 }
             }
             Debug.WriteLine("entropy: " + ((int)(num2 * 100.0)) + "%");
         }
     }
     finally
     {
         base.Dispose(disposing);
     }
 }
コード例 #11
0
        public Paperang(BaseTypes.Connection connection, BaseTypes.Model model)
        {
            switch (connection)
            {
            case BaseTypes.Connection.USB:
                Printer   = new USB(model);
                Transform = new Transforms(new BaseTypes.Packet {
                    Start = 0x02,
                    End   = 0x03
                }, new BaseTypes.Opcodes {
                    NoOp        = new byte[] { 0x06, 0x00, 0x02, 0x00 },
                    Print       = new byte[] { 0x00, 0x01, 0x00, 0x00 },
                    LineFeed    = new byte[] { 0x1a, 0x00, 0x02, 0x00 },
                    TransmitCrc = new byte[] { 0x18, 0x01, 0x04, 0x00 }
                }, 4);
                Crc = new CRC(0x77c40d4d ^ MagicValue);
                break;

            default:
                throw new PrinterConnectionNotSupportedException();
            }
        }
コード例 #12
0
        internal void InitializeForSend(IController parent, Converter converter, uint cmd, uint flags, object payload)
        {
            Packet header = parent.NewPacket();

            header.Cmd   = cmd;
            header.Flags = flags;

            _parent = parent;

            _raw          = new MessageRaw();
            _base         = new MessageBase();
            _base.Header  = header;
            _base.Payload = payload;

            if (payload != null)
            {
                _raw.Payload = converter.Serialize(payload);

                _base.Header.Size    = (uint)_raw.Payload.Length;
                _base.Header.CrcData = CRC.ComputeCRC(_raw.Payload, 0);
            }
        }
コード例 #13
0
        public void CRCTest()
        {
            var SampleReq = new byte[]
            {
                0x01,
                0x0F,
                0x00,
                0x13,
                0x00,
                0x0A,
                0x02,
                0xCD,
                0x01,
                0x72,   // CRC Lo
                0xCB,   // CRC Hi
            };

            ushort ExpectedCRC = 0xCB72;

            Assert.AreEqual(ExpectedCRC, CRC.Get(SampleReq, 9));
            Assert.AreEqual(0, CRC.Get(SampleReq));
        }
コード例 #14
0
ファイル: ASHProtocol.cs プロジェクト: lenloe1/Stuff
        /// <summary>
        /// Calculates the current CRC for the data
        /// </summary>
        /// <returns>The current CRC</returns>
        //  Revision History
        //  MM/DD/YY Who Version Issue# Description
        //  -------- --- ------- ------ -------------------------------------------
        //  08/09/11 RCG 2.52.00        Created

        private ushort CalculateCurrentCRC()
        {
            byte[] DataToCRC;
            int    CRCDataLength = 1;

            if (m_Data != null)
            {
                CRCDataLength += m_Data.Length;
            }

            DataToCRC = new byte[CRCDataLength];

            DataToCRC[0] = m_ControlByte;

            if (DataToCRC.Length > 1)
            {
                byte[] RandomizedData = RandomizeData(m_Data);
                Array.Copy(RandomizedData, 0, DataToCRC, 1, RandomizedData.Length);
            }

            return(CRC.CalculateCRC16(DataToCRC));
        }
コード例 #15
0
ファイル: OcaMarHelper.cs プロジェクト: zykitzy/TiWen
 /// <summary>
 /// 发送事件片数据
 /// </summary>
 /// <param name="buffer"></param>
 /// <param name="callNumber"></param>
 /// <returns></returns>
 public static byte[] GetTagID(byte[] buffer, int callNumber)
 {
     byte[] command = new byte[16];
     command[0] = 0x3E;
     command[1] = 0x0c + 1;
     command[2] = 0xA9;
     //复制基站ID 和 标签ID
     for (int i = 3; i <= 10; i++)
     {
         command[i] = buffer[i];
     }
     command[11] = 0x30;
     command[12] = (byte)callNumber;
     byte[] crc = new byte[command.Length - 4];
     Buffer.BlockCopy(command, 1, crc, 0, command.Length - 4);
     byte[] convertCrc = BitConverter.GetBytes(CRC.CCITT_CRC16(crc));
     //颠倒高低位
     command[13] = convertCrc[1];
     command[14] = convertCrc[0];
     command[15] = 0x3F;
     return(command);
 }
コード例 #16
0
ファイル: APNGLoader.cs プロジェクト: rumkex/Calcifer
            /// <summary>
            /// Attempts to parse an APNGChunk for the specified stream
            /// </summary>
            /// <param name="stream">The stream containing the APNG Chunk</param>
            public void Read(Stream stream)
            {
                if (!stream.CanRead)
                {
                    throw new ArgumentException("Stream is not readable");
                }

                calculatedCRC = CRC.InitialCRC;

                long chunkStart = stream.Position;

                // Read the data Length
                chunkLength = Utils.ReadStream(stream, 4);

                // Read the chunk type
                chunkType     = Utils.ReadStream(stream, 4);
                calculatedCRC = CRC.UpdateCRC(calculatedCRC, chunkType);

                // Read the data
                chunkData     = Utils.ReadStream(stream, ChunkLength);
                calculatedCRC = CRC.UpdateCRC(calculatedCRC, chunkData);

                // Read the CRC
                chunkCRC = Utils.ReadStream(stream, 4);

                // CRC is inverted
                calculatedCRC = ~calculatedCRC;

                // Verify the CRC
                if (ChunkCRC != calculatedCRC)
                {
                    var sb = new StringBuilder();
                    sb.AppendLine(String.Format("APNG Chunk CRC Mismatch.  Chunk CRC = {0}, Calculated CRC = {1}.",
                                                ChunkCRC, calculatedCRC));
                    sb.AppendLine(String.Format("This occurred while parsing the chunk at position {0} (0x{1:X8}) in the stream.",
                                                chunkStart, chunkStart));
                    throw new ApplicationException(sb.ToString());
                }
            }
コード例 #17
0
        /// <summary>
        /// 处理资料列表
        /// </summary>
        private void ProcessSoftList()
        {
            foreach (var item in fileList)
            {
                FileInfo fi       = new FileInfo(item.PhyFilePath);
                int      SleepCnt = 10;//循环检测内存剩余计数器
                //判断是否还有剩余内存
                while (SleepCnt > 0 && GetFreeMemory(fi.Length) < 0)
                {
                    Thread.Sleep(1000);
                    SleepCnt--;
                    //超时抛异常
                    if (SleepCnt <= 0)
                    {
                        GC.Collect();
                        throw new OutOfMemoryException();
                    }
                }
                switch (_config.CRCLevel)
                {
                case Const.EnumCRCLevel.Default:
                    break;

                case Const.EnumCRCLevel.Auto:
                    if (item.CRC32 == DefaultCRC)
                    {
                        item.CRC32 = CRC.Crc32BytesForPath(item.PhyFilePath);
                    }
                    break;

                case Const.EnumCRCLevel.RealTime:
                    item.CRC32 = CRC.Crc32BytesForPath(item.PhyFilePath); break;

                default:
                    item.CRC32 = CRC.Crc32BytesForPath(item.PhyFilePath); break;
                }
                item.FileSize = (int)fi.Length;
            }
        }
コード例 #18
0
        /// <summary>
        /// 发送指令:售币机初始化
        /// </summary>
        public void SendInit()
        {
            recvBuf = new List <byte>();

            List <byte> sendData = new List <byte>();

            sendData.Add(0x68);
            sendData.Add(0x01);
            sendData.Add(0x06);
            sendData.Add((byte)(SerialAPI.CanWork1 == "1" ? 1 : 0));
            sendData.Add((byte)(SerialAPI.CanWork2 == "1" ? 1 : 0));
            sendData.Add((byte)Motor1Coin);
            sendData.Add((byte)Motor2Coin);
            sendData.Add((byte)WorkType);          //1四位2六位
            sendData.Add((byte)(DigitEn ? 1 : 0)); //数字币二合一售币机
            ushort crcValue = CRC.Crc16(sendData.ToArray(), (byte)sendData.Count);

            sendData.AddRange(BitConverter.GetBytes(crcValue));
            sendData = AddHeadEnd(sendData);

            com.Write(sendData.ToArray(), 0, sendData.Count);
        }
コード例 #19
0
        internal void InitializeForSend(IController parent, Converter converter, uint cmd, uint flags, object payload)
        {
            Packet header = parent.NewPacket();

            header.m_cmd   = cmd;
            header.m_flags = flags;

            m_parent = parent;

            m_raw            = new MessageRaw();
            m_base           = new MessageBase();
            m_base.m_header  = header;
            m_base.m_payload = payload;

            if (payload != null)
            {
                m_raw.m_payload = converter.Serialize(payload);

                m_base.m_header.m_size    = (uint)m_raw.m_payload.Length;
                m_base.m_header.m_crcData = CRC.ComputeCRC(m_raw.m_payload, 0);
            }
        }
コード例 #20
0
            private void WriteHeader()
            {
                const string chunkType = "IHDR";
                var          ihdrBytes = new List <byte>();

                //Create PNG header
                ihdrBytes.AddRange(GetIntBytes(_imageWidth));
                ihdrBytes.AddRange(GetIntBytes(_imageHeight));
                ihdrBytes.Add(BitDepth);
                ihdrBytes.Add(ColourType);
                ihdrBytes.Add(CompressionMethod);
                ihdrBytes.Add(FilterMethod);
                ihdrBytes.Add(InterlaceMethod);

                byte[] header = CreateChunkHeader(chunkType, ihdrBytes.Count);
                _outputStream.Write(header, 0, header.Length);

                _outputStream.Write(ihdrBytes.ToArray(), 0, ihdrBytes.Count);

                byte[] footer = CreateChunkFooter(CRC.Calculate(StringToBytes(chunkType), ihdrBytes.ToArray()));
                _outputStream.Write(footer, 0, footer.Length);
            }
コード例 #21
0
        public bool Send(byte command, byte[] text)
        {
            bool bb = false;

            try
            {
                if (DT == DataType.json)
                {
                    return(Send(command, System.Text.Encoding.UTF8.GetString(text)));
                }
                else if (DT == DataType.bytes)
                {
                    byte[] sendb = text;
                    byte[] lens  = ConvertToByteList(sendb.Length);
                    byte[] b     = new byte[2 + 2 + lens.Length + sendb.Length];
                    b[0] = command;
                    b[1] = (byte)lens.Length;
                    lens.CopyTo(b, 2);
                    CRC.ConCRC(ref b, 2 + lens.Length);
                    sendb.CopyTo(b, 2 + 2 + lens.Length);
                    bb = Send(b);
                }
                else
                {
                    return(Send(text));
                }
            }
            catch (Exception ee)
            {
                Isline = false;
                Stop();
                Timeoutevent?.Invoke();
                Timeoutobjevent?.Invoke(this);
                Send(command, text);
                ErrorMge(9, "send:" + ee.Message);
                return(false);
            }
            return(bb);
        }
コード例 #22
0
        /// <summary>
        /// 8,对外接口:获取报警记录
        /// </summary>
        public static void GetWarningRecord()
        {
            if (EventClass.GetInstance()._ConnectBleAddress == "")
            {
                MessageBox.Show("尚未连接蓝牙门锁", "系统提示");
                return;
            }
            string str = GlobalParams._getWarningDataBody;

            if (str.Length % 2 != 0)
            {
                str = "0" + str;
            }
            byte[] val = new byte[str.Length / 2];
            for (int i = 0; i < val.Length; i++)
            {
                string b = str.Substring(i * 2, 2);
                val[i] = Convert.ToByte(b, 16);
            }
            //CRC
            byte[] send     = new byte[val.Length + 1];
            byte[] crcBytes = new byte[val.Length - 2];
            for (int i = 0; i < send.Length; i++)
            {
                send[i] = byte.MaxValue;
            }
            for (int k = 0; k < val.Length; k++)
            {
                send[k] = val[k];
            }
            for (int j = 0; j < crcBytes.Length; j++)
            {
                crcBytes[j] = val[j + 2];
            }
            send[val.Length] = CRC.Crc8(crcBytes);
            EventClass.GetInstance().val_GetRecord = send;
            EventClass.GetInstance().WriteCommand(send);
        }
コード例 #23
0
        public CmdSuperCmd(SuperCmdInfo info)
        {
            KEY       = "CMD";
            BODY_KEY  = "BYPASS";
            CLINET_ID = info.client_id;

            List <byte> lst = new List <byte>();

            //控制器地址
            lst.Add(0xFA);
            //命令类型
            lst.Add(info.type);
            //参数1
            lst.Add(0);
            //参数2
            lst.Add(0);
            //参数3
            lst.Add(0);
            //参数4
            lst.Add(0);
            //参数5
            lst.Add(0);
            //参数6
            lst.Add(0x00);
            //参数7
            lst.Add(0x00);
            //参数8
            lst.Add(0x00);
            //计算校验(控制可以直接使用的)
            string strCrc = CRC.ToModbusCRC16(lst.ToArray(), true);  //是否翻转

            //16进制,转成16进制显示
            foreach (var m in lst)
            {
                CONTENT += Convert.ToString(m, 16).ToUpper().PadLeft(2, '0');
            }
            CONTENT = info.regulator_id + " " + info.host_ip + " " + info.host_port + " " + CONTENT + strCrc;
        }
コード例 #24
0
ファイル: Program.cs プロジェクト: Daniel-McCarthy/Net-Hash
        static void testCustomInput(string input)
        {
            Console.WriteLine("Testing FNV1-Hash with string \"" + input + "\"");
            Console.WriteLine(FNV.fnv1_32Hash(stringToByteArray(input)));

            Console.WriteLine("Testing FNV1A-Hash with string \"" + input + "\"");
            Console.WriteLine(FNV.fnv1A_32Hash(stringToByteArray(input)));

            Console.WriteLine("Testing FNV0-Hash with string \"" + input + "\"");
            Console.WriteLine(FNV.fnv0_32Hash(stringToByteArray(input)) + '\n');

            Console.WriteLine("Testing CRC-Hash with string \"" + input + "\"");
            Console.WriteLine(CRC.crc_32Hash(stringToByteArray(input)));

            Console.WriteLine("Testing CRC-B-Hash with string \"" + input + "\"");
            Console.WriteLine(CRC.crcB_32Hash(stringToByteArray(input)) + '\n');

            Console.WriteLine("Testing Adler-Hash with string \"" + input + "\"");
            Console.WriteLine(Adler.adler_32Hash(stringToByteArray(input)) + '\n');

            Console.WriteLine("Testing MD2-Hash with string \"" + input + "\"");
            Console.WriteLine(MD.md2_128Hash(stringToByteArray(input)));

            Console.WriteLine("Testing MD4-Hash with string \"" + input + "\"");
            Console.WriteLine(MD.md4_128Hash(stringToByteArray(input)));

            Console.WriteLine("Testing MD5-Hash with string \"" + input + "\"");
            Console.WriteLine(MD.md5_128Hash(stringToByteArray(input)));

            Console.WriteLine("Testing SHA0-Hash with string \"" + input + "\"");
            Console.WriteLine(SHA.sha0_160Hash(stringToByteArray(input)) + '\n');

            Console.WriteLine("Testing SHA1-Hash with string \"" + input + "\"");
            Console.WriteLine(SHA.sha1_160Hash(stringToByteArray(input)) + '\n');

            Console.WriteLine("Testing SHA2-Hash with string \"" + input + "\"");
            Console.WriteLine(SHA.sha2_224Hash(stringToByteArray(input)));
        }
コード例 #25
0
        private bool VerifyHeader()
        {
            uint crc = _messageBase.Header.CrcHeader;
            bool fRes;


            // verify CRC32 only if connected device has reported that it implements it
            if (_parent.App.IsCRC32EnabledForWireProtocol)
            {
                // compute CRC32 with header CRC32 zeroed
                _messageBase.Header.CrcHeader = 0;

                fRes = CRC.ComputeCRC(_parent.CreateConverter().Serialize(_messageBase.Header), 0) == crc;

                _messageBase.Header.CrcHeader = crc;
            }
            else
            {
                fRes = true;
            }

            return(fRes);
        }
コード例 #26
0
ファイル: LzmaHelper.cs プロジェクト: yanhan-dev/BNSAtomix
        public static uint CRC32(Stream inStream)
        {
            CRC crc = new CRC();

            crc.Init();
            byte[] buf = new byte[1024];
            while (inStream.Position < inStream.Length)
            {
                int read;
                if (inStream.Position + 1024 < inStream.Length)
                {
                    read = 1024;
                }
                else
                {
                    read = (int)(inStream.Length - inStream.Position);
                }

                inStream.Read(buf, 0, read);
                crc.Update(buf, 0, (uint)read);
            }
            return(crc.GetDigest());
        }
コード例 #27
0
        /// <summary>
        /// Build a final compressed, encrypted, and encoded packet.
        /// </summary>
        /// <returns>The packet data.</returns>
        public byte[] BuildPacket()
        {
            // Get the packet data
            byte[] data = Data.ToArray();

            // Compression
            bool compressed = false;

            if (DataLength > 100)
            {
                byte[] compressedData = CompressionService.Compress(data);
                if (compressedData.Length < data.Length)
                {
                    data       = compressedData;
                    compressed = true;
                }
            }
            ushort dataLength = (ushort)data.Length;

            // Create the packet header
            InternalPacketHeader header = new InternalPacketHeader
            {
                OpCode     = OpCode,
                Compressed = compressed,
                Length     = dataLength
            };

            LastHeader = header;

            // Append the header and CRC to the compressed data
            ToffeePacket packet = new ToffeePacket(Sender);

            packet.Write(header);
            packet.Write(data, true);
            packet.Write(CRC.CalculateCRC32(data));
            return(packet.GetBytes());
        }
コード例 #28
0
        public AvlData Decode(IBitReader reader)
        {
            byte num = reader != null?reader.ReadByte() : throw new ArgumentNullException(nameof(reader));

            byte[] buffer = reader.ReadBytes(num);
            if (reader.ReadByte() != CRC.CalculateXor(buffer))
            {
                throw new Exception("AvlData Record CRC failure. Received CRC - {0}, calculated CRC - {1}.");
            }
            using (MemoryStream stream = new MemoryStream())
            {
                using (IBitReader suitableBitReader = stream.CreateSuitableBitReader())
                {
                    stream.Write(buffer, 0, num);
                    stream.Position = 0L;
                    long            timestamp = suitableBitReader.ReadUInt32() * 1000L;
                    AvlDataPriority priority  = (AvlDataPriority)suitableBitReader.ReadByte();
                    GpsElement      gps       = DefaultGpsElementEncoding.Instance.Decode(suitableBitReader);
                    IoElement       data      = DefaultIOElementEncoding.Instance.Decode(suitableBitReader);
                    DateTime        dateTime  = DateTimeExt.FromAvl(timestamp);
                    return(new AvlData(priority, dateTime, gps, data));
                }
            }
        }
コード例 #29
0
 public string FindPropertyNameByCRC28(uint crc)
 {
     foreach (FastPropertyName property in TexEnvs.Keys)
     {
         string hdrName = property.Value + HDRPostfixName;
         if (CRC.Verify28DigestUTF8(hdrName, crc))
         {
             return(hdrName);
         }
         string stName = property.Value + STPostfixName;
         if (CRC.Verify28DigestUTF8(stName, crc))
         {
             return(stName);
         }
         string texelName = property.Value + TexelSizePostfixName;
         if (CRC.Verify28DigestUTF8(texelName, crc))
         {
             return(texelName);
         }
     }
     foreach (FastPropertyName property in Floats.Keys)
     {
         if (property.IsCRC28Match(crc))
         {
             return(property.Value);
         }
     }
     foreach (FastPropertyName property in Colors.Keys)
     {
         if (property.IsCRC28Match(crc))
         {
             return(property.Value);
         }
     }
     return(null);
 }
コード例 #30
0
        private bool VerifyPayload()
        {
            if (_messageRaw.Payload == null)
            {
                return(_messageBase.Header.Size == 0);
            }
            else
            {
                if (_messageBase.Header.Size != _messageRaw.Payload.Length)
                {
                    return(false);
                }

                // verify CRC32 only if connected device has reported that it implements it
                if (_parent.App.IsCRC32EnabledForWireProtocol)
                {
                    return(CRC.ComputeCRC(_messageRaw.Payload, 0) == _messageBase.Header.CrcData);
                }
                else
                {
                    return(true);
                }
            }
        }
コード例 #31
0
    void WriteFile(string fileName)
    {
        fileName = fileName.Replace("\\", "/");
        string name = fileName.Substring(fileName.LastIndexOf('/') + 1, fileName.LastIndexOf('.') - fileName.LastIndexOf('/') - 1);

        if (!Directory.Exists(_dataPath))
        {
            Directory.CreateDirectory(_dataPath);
        }
        string outFile = _dataPath + name + ".bytes";

        FileStream output = new FileStream(outFile, FileMode.Create);

        SerializeCsvData();

        int crc = (int)CRC.CalculateDigest(_serializeStream.GetBuffer(), 0, (uint)_serializeStream.Length);

        output.Write(BitConverter.GetBytes(crc), 0, sizeof(int));

        output.Write(_serializeStream.GetBuffer(), 0, (int)_serializeStream.Length);

        output.Flush();
        output.Close();
    }
コード例 #32
0
        private CRC detectAndCorrect(int start, int end)
        {
            RadioLog.Common.SafeBitArray original = mMessage.CloneFromIndexToIndex(start, end);

            CRC retVal = CRCFleetsync.check(original);

            //Attempt to correct single-bit errors
            if (retVal == CRC.FAILED_PARITY)
            {
                int[] errorBitPositions = CRCFleetsync.findBitErrors(original);

                if (errorBitPositions != null)
                {
                    foreach (int errorBitPosition in errorBitPositions)
                    {
                        mMessage.flip(start + errorBitPosition);
                    }

                    retVal = CRC.CORRECTED;
                }
            }

            return(retVal);
        }
コード例 #33
0
 public void Save(Transform t)
 {
     CRC cr = new CRC();
     cr.t = t;
     var j = t.GetComponent<CharacterJoint>();
     if (j != null)
         cr.CharacterJoint2 = new CharacterJoint2() { connectedBody = j.connectedBody.name, anchor = j.anchor, axis = j.axis, highTwistLimit = j.highTwistLimit, lowTwistLimit = j.lowTwistLimit, rotationDrive = j.rotationDrive, swing1Limit = j.swing1Limit, swing2Limit = j.swing2Limit, swingAxis = j.swingAxis, targetAngularVelocity = j.targetAngularVelocity, targetRotation = j.targetRotation };
     Destroy(j);
     var r = t.rigidbody;
     if (r != null)
     {
         var rigidbody2 = new Rigidbody2() { mass = r.mass };
         cr.Rigidbody2 = rigidbody2;
     }
     Destroy(r);
     var c = t.collider;
     var bc = c as BoxCollider;
     if (bc != null)
         cr.BoxCollider2 = new BoxCollider2() { center = bc.center, extents = bc.extents };
     var sc = c as SphereCollider;
     if (sc != null)
         cr.SphereCollider2 = new SphereCollider2() { center = sc.center, radius = sc.radius };
     var cc = c as CapsuleCollider;
     if (cc != null)
         cr.CapsuleCollider2 = new CapsuleCollider2() { center = cc.center, direction = cc.direction, height = cc.height, radius = cc.radius };
     Destroy(c);
     crcs.Add(cr);
 }
コード例 #34
0
ファイル: PNG.cs プロジェクト: ChrisJamesSadler/Cosmos
 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);
 }