当前位置: 首页>>代码示例>>C#>>正文


C# Byte.Skip方法代码示例

本文整理汇总了C#中System.Byte.Skip方法的典型用法代码示例。如果您正苦于以下问题:C# Byte.Skip方法的具体用法?C# Byte.Skip怎么用?C# Byte.Skip使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Byte的用法示例。


在下文中一共展示了Byte.Skip方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: ParseResponse

 private void ParseResponse(Byte[] rawResponse)
 {
     packetId = rawResponse[1];
     errorCode = GetAsByte(rawResponse, 4);
     commandData = new List<String>(GetCommandDataFields(rawResponse));
     isCrcValid = 
         GetAsByte(rawResponse, rawResponse.Length - 2) ==
         rawResponse.Skip(1).Take(rawResponse.Length - 3).CalculateCrc();
 }
开发者ID:Dennis-Petrov,项目名称:Cash,代码行数:9,代码来源:Response.cs

示例2: FileReceiver

        //Метод потока
        protected void FileReceiver()
        {
            //Создаем Listener на порт "по умолчанию"
            TcpListener Listen = new TcpListener(6999);
            //Начинаем прослушку
            Listen.Start();
            //и заведем заранее сокет
            Socket ReceiveSocket;
            while (true)
            {
                try
                {
                    //Пришло сообщение
                    ReceiveSocket = Listen.AcceptSocket();
                    Byte[] Receive = new Byte[256];
                    //Читать сообщение будем в поток
                    using (MemoryStream MessageR = new MemoryStream())
                    {
                        
                        //Количество считанных байт
                        Int32 ReceivedBytes;
                        Int32 Firest256Bytes = 0;
                        String FilePath = "";
                        do
                        {//Собственно читаем
                            ReceivedBytes = ReceiveSocket.Receive(Receive, Receive.Length, 0);
                            //Разбираем первые 256 байт
                            if (Firest256Bytes < 256) 
                            {
                                Firest256Bytes += ReceivedBytes;
                                Byte[] ToStr = Receive;
                                //Учтем, что может возникнуть ситуация, когда они не могу передаться "сразу" все
                                if (Firest256Bytes > 256)
                                {
                                    Int32 Start = Firest256Bytes - ReceivedBytes;
                                    Int32 CountToGet = 256 - Start;
                                    Firest256Bytes = 256;
                                    //В случае если было принято >256 байт (двумя сообщениями к примеру)
                                    //Остаток (до 256) записываем в "путь файла"
                                    ToStr = Receive.Take(CountToGet).ToArray();
                                    //А остальную часть - в будующий файл
                                    Receive = Receive.Skip(CountToGet).ToArray();
                                    MessageR.Write(Receive, 0, ReceivedBytes);
                                }
                                //Накапливаем имя файла
                                FilePath += Encoding.Default.GetString(ToStr);
                            } else

                            //и записываем в поток
                            MessageR.Write(Receive, 0, ReceivedBytes);
                            //Читаем до тех пор, пока в очереди не останется данных
                        } while (ReceivedBytes == Receive.Length);
                        //Убираем лишние байты
                        String resFilePath = FilePath.Substring(0, FilePath.IndexOf('\0'));
                        using (var File = new FileStream(resFilePath, FileMode.Create))
                        {//Записываем в файл
                            File.Write(MessageR.ToArray(), 0, MessageR.ToArray().Length);
                        }//Уведомим пользователя
                        ChatBox.BeginInvoke(AcceptDelegate, new object[] { "Received: " + resFilePath, ChatBox });
                    }
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }

            }
        }
开发者ID:Pashahasband,项目名称:SpaceKurs,代码行数:69,代码来源:Form1.cs

示例3: dmpInitialize


//.........这里部分代码省略.........
            setRate(4); // 1khz / (1 + 4) = 200 Hz

            DEBUG_PRINTLN(F("Setting external frame sync to TEMP_OUT_L[0]..."));
            setExternalFrameSync(MPU6050_EXT_SYNC_TEMP_OUT_L);

            DEBUG_PRINTLN(F("Setting DLPF bandwidth to 42Hz..."));
            setDLPFMode(MPU6050_DLPF_BW_42);

            DEBUG_PRINTLN(F("Setting gyro sensitivity to +/- 2000 deg/sec..."));
            setFullScaleGyroRange(MPU6050_GYRO_FS_2000);

            DEBUG_PRINTLN(F("Setting DMP configuration bytes (function unknown)..."));
            setDMPConfig1(0x03);
            setDMPConfig2(0x00);

            DEBUG_PRINTLN(F("Clearing OTP Bank flag..."));
            setOTPBankValid(false);

            DEBUG_PRINTLN(F("Setting X/Y/Z gyro offsets to previous values..."));
            setXGyroOffset(xgOffset);
            setYGyroOffset(ygOffset);
            setZGyroOffset(zgOffset);

            DEBUG_PRINTLN(F("Setting X/Y/Z gyro user offsets to zero..."));
            setXGyroOffsetUser(0);
            setYGyroOffsetUser(0);
            setZGyroOffsetUser(0);

            DEBUG_PRINTLN(F("Writing final memory update 1/7 (function unknown)..."));
            uint8_t[] dmpUpdate = new uint8_t[16];
            int j;
            uint16_t pos = 0;
            for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(dmpUpdates[pos]);
            writeMemoryBlock(dmpUpdate.Skip(3).ToArray(), dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);

            DEBUG_PRINTLN(F("Writing final memory update 2/7 (function unknown)..."));
            for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(dmpUpdates[pos]);
            writeMemoryBlock(dmpUpdate.Skip(3).ToArray(), dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);

            DEBUG_PRINTLN(F("Resetting FIFO..."));
            resetFIFO();

            DEBUG_PRINTLN(F("Reading FIFO count..."));
            uint8_t fifoCount = (byte)getFIFOCount();
            uint8_t[] fifoBuffer = new uint8_t[10 * 128];

            if (fifoCount > 0)
            {
                printf("Current FIFO count=" + fifoCount);
                getFIFOBytes(fifoBuffer, fifoCount);
            }
            else
                DEBUG_PRINTLN("fifiCount=0!!");

            DEBUG_PRINTLN(F("Setting motion detection threshold to 2..."));
            setMotionDetectionThreshold(2);

            DEBUG_PRINTLN(F("Setting zero-motion detection threshold to 156..."));
            setZeroMotionDetectionThreshold(156);

            DEBUG_PRINTLN(F("Setting motion detection duration to 80..."));
            setMotionDetectionDuration(80);

            DEBUG_PRINTLN(F("Setting zero-motion detection duration to 0..."));
            setZeroMotionDetectionDuration(0);
开发者ID:brookpatten,项目名称:MrGibbs,代码行数:66,代码来源:MPU6050MotionApps.cs

示例4: FileReceiver

        //Метод потока
        protected void FileReceiver()
        {
            //Создаем Listener на порт "по умолчанию"
            TcpListener Listen = new TcpListener(Int32.Parse(PORT.Text));
            //и заведем заранее сокет
            Socket ReceiveSocket;
            try
            {
                //Начинаем прослушку
                Listen.Start();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            while (true)
            {
                try
                {
                    //Пришло сообщение
                    ReceiveSocket = Listen.AcceptSocket();
                    Byte[] Receive = new Byte[QuantityByteInStep];
                    //Читать сообщение будем в поток
                    using (MemoryStream MessageR = new MemoryStream())
                    {

                        //Количество считанных байт
                        Int32 ReceivedBytes;
                        Int32 FirestQuantityByteInStepBytes = 0;
                        String FilePath = "";
                        //Если true, то первые QuantityByteInStep прочитаны
                        bool firstBytes = false;

                        string resFilePath = "";
                        string resFileSize = "";

                        do
                        {//Собственно читаем
                            ReceivedBytes = ReceiveSocket.Receive(Receive, Receive.Length, 0);
                            //Разбираем первые QuantityByteInStep байт
                            if (FirestQuantityByteInStepBytes < QuantityByteInStep)
                            {
                                FirestQuantityByteInStepBytes += ReceivedBytes;
                                Byte[] ToStr = Receive;
                                //Учтем, что может возникнуть ситуация, когда они не могу передаться "сразу" все
                                if (FirestQuantityByteInStepBytes > QuantityByteInStep)
                                {
                                    Int32 Start = FirestQuantityByteInStepBytes - ReceivedBytes;
                                    Int32 CountToGet = QuantityByteInStep - Start;
                                    FirestQuantityByteInStepBytes = QuantityByteInStep;
                                    //В случае если было принято >QuantityByteInStep байт (двумя сообщениями к примеру)
                                    //Остаток (до QuantityByteInStep) записываем в "путь файла"
                                    ToStr = Receive.Take(CountToGet).ToArray();
                                    //А остальную часть - в будующий файл
                                    Receive = Receive.Skip(CountToGet).ToArray();
                                    MessageR.Write(Receive, 0, ReceivedBytes);
                                    firstBytes = true;
                                }
                                //Накапливаем имя файла
                                FilePath += Encoding.Default.GetString(ToStr);

                            }
                            else
                            {
                                if (firstBytes || FirestQuantityByteInStepBytes == QuantityByteInStep)
                                {
                                    //Уже можем прочитать имя и разме рфайла
                                    //Убираем лишние байты
                                    String resFilePathAndFileSize = FilePath.Substring(0, FilePath.IndexOf('\0'));
                                    char[] separators = { '^' };
                                    string[] words = resFilePathAndFileSize.Split(separators);
                                    resFilePath = words[0];
                                    resFileSize = words[1];
                                    firstBytes = false;
                                    FirestQuantityByteInStepBytes = QuantityByteInStep + 1;
                                    ChatBox.BeginInvoke(AcceptDelegate, new object[] { "Началось принятие файла. " + resFilePath, ChatBox });
                                }
                                //и записываем в поток
                                MessageR.Write(Receive, 0, ReceivedBytes);
                            }
                            //Читаем до тех пор, пока в очереди не останется данных
                        } while (ReceivedBytes > 0);

                        string tempFilePath;
                        if (filePath != "")
                        {
                            tempFilePath = filePath + "//" + resFilePath;
                        }
                        else
                        {
                            tempFilePath = resFilePath;
                        }

                        using (var File = new FileStream(tempFilePath, FileMode.Create))
                        {
                            //Записываем в файл
                            File.Write(MessageR.ToArray(), 0, MessageR.ToArray().Length);

//.........这里部分代码省略.........
开发者ID:HelloV,项目名称:network-lab1,代码行数:101,代码来源:Form1.cs

示例5: DeserializeData

        /// <summary>
        /// Deserializes passed binary data.
        /// </summary>
        /// <param name="lInputData"><see cref="Byte[]"/> of data you want to serialize.</param>
        /// <param name="InitalOffset">Offset where you want to start serialization as <see cref="int"/></param>
        /// <param name="NewOffset"Offset where serialization ended as <see cref="int"/></param>
        /// <returns>Serialized objects as <see cref="object[]"/></returns>
        public virtual object[] DeserializeData(Byte[] lInputData, int InitalOffset, ref int NewOffset, int startType = 0, int endType = 0)
        {
            int offset = InitalOffset;
            List<object> OutputStructures = new List<object>();
            int loffset = 0;
            uint ManyParse = 0;
            bool ManyParseCondition = false;

            if (endType == 0)
                endType = cSerializableTypes.Count();

            //Check the bounds of start and end.
            if (startType > cSerializableTypes.Count() - 1 || endType > cSerializableTypes.Count())
                return null;

            for (int x = startType; x < endType; )
            {
                Type CurrentType = cSerializableTypes[x];
                if (offset >= lInputData.Count())
                {
                    log.Error("Offset is bigger than data count");
                    return null;
                }

                switch (CurrentType.Name)
                {
                    case "VarByte":
                        ManyParseCondition = true;
                        CurrentType = typeof(Byte);
                        break;//Go to next export round
                    case "VarUInt16":
                        ManyParseCondition = true;
                        CurrentType = typeof(UInt16);
                        break;//Go to next export round
                    case "VarUInt32":
                        ManyParseCondition = true;
                        CurrentType = typeof(UInt32);
                        break;//Go to next export round
                }
                switch (CurrentType.Name)
                {
                    case "String":
                        string strdata = ByteArrayToString(lInputData.Skip(offset).ToArray());
                        if (strdata == null)
                        {
                            log.Error("Problems while deserializing to String");
                            return null;
                        }
                        OutputStructures.Add(strdata);
                        loffset = strdata.Length + 1;
                        break;
                    case "Byte[]":
                        Byte[] bytedata = lInputData.Skip(offset).ToArray();
                        OutputStructures.Add(bytedata);
                        loffset = bytedata.Length;
                        break;
                    default:
                        //We must get size or we get error.
                        object result = ByteArrayToStructure(lInputData.Skip(offset).ToArray(), CurrentType, ref loffset);
                        if (result == null)
                        {
                            List<Type> t= new List<Type>();
                            foreach (System.Reflection.FieldInfo prop in CurrentType.GetFields())
                                t.Add(prop.FieldType);

                            object[] allData= (new BinarySerializer(t.ToArray())).DeserializeData(lInputData.Skip(offset).ToArray(), loffset, ref loffset);
                            int m=0;
                            object o = Activator.CreateInstance(CurrentType);
                            foreach (System.Reflection.FieldInfo prop in CurrentType.GetFields())
                            {
                                prop.SetValue(o, allData[m]);
                                m++;
                            }
                            log.Error("Problems while deserializing to unkown type");
                            return null;
                        }
                        OutputStructures.Add(result);
                        break;
                }

                offset += loffset;
                loffset = 0;

                if (ManyParseCondition)
                {
                    ManyParse = (uint)Convert.ChangeType(OutputStructures.Last(), typeof(uint));
                    ManyParseCondition = false;
                    x++;
                }
                else
                {
                    if (ManyParse > 1)
                        ManyParse--;
//.........这里部分代码省略.........
开发者ID:offlinehacker,项目名称:Bastet-GUI,代码行数:101,代码来源:BinarySerializer.cs

示例6: DataRecord_Unit_GetBytes_LengthExceedsDataSize

        public void DataRecord_Unit_GetBytes_LengthExceedsDataSize()
        {
            Byte[] value = new Byte[] { 1, 2, 3, 4, 5 };
            DataRecord target = DataRecordTests.CreateDataRecord(new String[] { "FirstName", "LastName", "MyValue" }, new Object[] { "Chad", "Greer", value });
            Int32 i = 2;
            Int64 dataIndex = 4;
            Byte[] buffer = new Byte[value.Length];
            Int32 bufferIndex = 0;
            Int32 length = value.Length - (Int32)dataIndex + 1;

            Int64 expected = value.Length - (Int32)dataIndex;
            Int64 actual = target.GetBytes(i, dataIndex, buffer, bufferIndex, length);
            Assert.AreEqual(expected, actual);
            CollectionAssert.AreEquivalent(value.Skip((Int32)dataIndex).Concat(Enumerable.Range(0, (Int32)dataIndex).Select(j => (Byte)0)).ToArray(), buffer);
        }
开发者ID:cegreer,项目名称:Common,代码行数:15,代码来源:DataRecordTests.cs

示例7: GetMessage

        public int GetMessage(byte[] prvkey, byte[] pubkey, Action<Message>store)
        {
            int count = 0;
            sw.WriteByte((byte)ClientServerCmd.GetMessage);
            SendPublicKey(pubkey);

            RSAParameters rsap;
            Shared.LoadKey2(Shared.prvToPem(prvkey), null, out rsap);
            Shared.AnswerRemotePubkeyTest(sr, sw, rsap);

            while (true)
            {
                var resp = sr.ReadByte();
                if (resp == (byte)ClientServerCmd.NoMessage)
                    return count;
                else if (resp != (byte)ClientServerCmd.HasMessage)
                    throw new Exception();
                var len = sr.ReadShort();
                if (len > 1024)
                    throw new Exception();
                var buf = new Byte[len];
                //sr.Read(buf, 0, 8);
                //var ts = BitConverter.ToInt64(buf, 0);
                //DateTime.FromFileTimeUtc(ts);
                if (sr.Read(buf, 0, len) != len)
                    throw new Exception();

                byte[] aeskey,aesIV,aesbuf;
                using (var rsa = new RSACryptoServiceProvider())
                {
                    rsa.ImportParameters(rsap);
                    var rsalen = 128;
                    var rsabuf = buf.Take(rsalen).ToArray();
                    aesbuf = buf.Skip(rsalen).ToArray();
                    var aes_keyivdata = rsa.Decrypt(rsabuf, false);
                    aeskey = aes_keyivdata.Take(32).ToArray();
                    aesIV = aes_keyivdata.Skip(32).Take(16).ToArray();
                }
                var msg=DecodeMessage(aesbuf,aeskey, aesIV, rsap, pubkey);
                store(msg);
                count++;
                sw.WriteByte((Byte)ClientServerCmd.Success);
            }
        }
开发者ID:RSA-PM,项目名称:RSA-PM,代码行数:44,代码来源:Client.cs


注:本文中的System.Byte.Skip方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。