CopyTo() публичный Метод

public CopyTo ( Array array, int index ) : void
array Array
index int
Результат void
        public static Byte[] GenerateHeader(Boolean fin, Boolean rsv1, Boolean rsv2, Boolean rsv3, Boolean opt4, Boolean opt3, Boolean opt2, Boolean opt1, Boolean mask)
        {
            Boolean[] header1 = new Boolean[8];
            header1[7] = fin;
            header1[6] = rsv1;
            header1[5] = rsv2;
            header1[4] = rsv3;
            header1[3] = opt4;
            header1[2] = opt3;
            header1[1] = opt2;
            header1[0] = opt1;

            Boolean[] header2 = new Boolean[8];
            header2[7] = mask;
            header2[6] = false;
            header2[5] = false;
            header2[4] = false;
            header2[3] = false;
            header2[2] = false;
            header2[1] = false;
            header2[0] = false;


            BitArray bitArray1 = new BitArray(header1);
            Byte[] byteHead = new Byte[2];
            bitArray1.CopyTo(byteHead, 0);

            BitArray bitArray2 = new BitArray(header2);
            bitArray2.CopyTo(byteHead, 1);

            return byteHead;
        }
Пример #2
0
 /// <summary>
 ///     将一个BitArray拼接在当前对象之前
 /// </summary>
 /// <param name="current"></param>
 /// <param name="before"></param>
 /// <returns></returns>
 public static BitArray Prepend(this BitArray current, BitArray before)
 {
     var bools = new bool[current.Length + before.Length];
     before.CopyTo(bools, 0);
     current.CopyTo(bools, before.Length);
     return new BitArray(bools);
 }
Пример #3
0
        public byte[] Serialize(string s)
        {
            var ba = new System.Collections.BitArray(s.Length * Base);

            int pos = 0;

            foreach (var c in s)
            {
                int mask = 1;
                int val  = chars.IndexOf(c) + 1;
                if (val == 0)
                {
                    throw new ArgumentException();
                }
                for (int i = 0; i < Base; i++)
                {
                    if ((val & mask) > 0)
                    {
                        ba[pos] = true;
                    }
                    mask <<= 1;
                    pos++;
                }
            }

            int len = (int)Math.Ceiling((ba.Length + Base) / 8d);

            byte[] arr = new byte[len];

            ba.CopyTo(arr, 0);

            return(arr);
        }
 private static BitArray AppendBitArray(BitArray original, BitArray appended)
 {
     var bools = new bool[original.Count + appended.Count];
     original.CopyTo(bools, 0);
     appended.CopyTo(bools, original.Count);
     return new BitArray(bools);
 }
Пример #5
0
        public static BitArray CopyBitArrayValueWise(BitArray a)
        {
            bool[] bits = new bool[a.Count];

            a.CopyTo(bits, 0);
            return new BitArray(bits);
        }
Пример #6
0
        public static void WriteBitArray(this BinaryWriter writer, BitArray buffer, int Len)
        {
            byte[] bufferarray = new byte[Convert.ToByte((buffer.Length + 8) / 8) + 1];
            buffer.CopyTo(bufferarray, 0);

            WriteBytes(writer, bufferarray.ToArray(), Len);
        }
Пример #7
0
 /// <summary>
 /// Mutates a gene by bitwise mutation.
 /// </summary>
 /// <param name="gene"></param>
 /// <returns></returns>
 public static Gene Mutate(Gene gene)
 {
     if ( gene is BinaryGene )
     {
         BinaryGene g = (BinaryGene) gene.Clone();
         g.Value = !(BinaryGene)gene;
         return g;
     }
     else if ( gene is DoubleGene )
     {
         DoubleGene g = (DoubleGene) gene.Clone();
         byte[] bytes = BitConverter.GetBytes(g.Value);
         BitArray ba = new BitArray(bytes);
         int p = Utils.Rand.Next( ba.Length );
         ba.Set(p, !ba[p]);
         ba.CopyTo(bytes, 0);
         g.Value = BitConverter.ToDouble(bytes,0);
         return g;
     }
     else if ( gene is IntegerGene )
     {
         IntegerGene g = (IntegerGene) gene.Clone();
         byte[] bytes = BitConverter.GetBytes(g.Value);
         BitArray ba = new BitArray(bytes);
         int p = Utils.Rand.Next( ba.Length );
         ba.Set(p, !ba[p]);
         ba.CopyTo(bytes, 0);
         g.Value = BitConverter.ToInt32(bytes,0);
         return g;
     }
     return (Gene) gene.Clone(); // default
 }
Пример #8
0
        public int BinarySub(int a, int b)
        {
            bool Cin = false;
            BitArray A = new BitArray(new int[] { a });
            BitArray B = new BitArray(new int[] { b });
            BitArray C = new BitArray(0);
            A.Length = wordLength;
            B.Length = wordLength;
            C.Length = wordLength;

            //Console.WriteLine("Subtracting " + a + " and " + b);
            for (int i = 0; i < wordLength; i++)
            {
                myALU.SetInput("C", BoolToVolt(Cin));
                myALU.SetInput("A", BoolToVolt(A[i]));
                myALU.SetInput("B", BoolToVolt(B[i]));
                myALU.UpdateOutputs();
                C[i] = VoltToBool(myALU.GetOutput("SubResult"));
                //Console.WriteLine(C[i] + " = " + A[i] + " + " + B[i]);
                Cin = VoltToBool(myALU.GetOutput("SubCarry"));
            }

            int[] value = new int[1];
            C.CopyTo(value, 0);
            return value[0];
        }
Пример #9
0
        public static bool verificarPermissao(Type tipoEntidadeVerificar, string chavePerfilCripto)
        {
            bool resultadoVerificacao = false;
            BitArray arrayChaveDecripto = null;
            byte[] preChavePerfilDecripto = new byte[ControladorAcesso.tamanhoChavePerfil];
            bool[] chavePerfilDecripto = new bool[ControladorAcesso.tamanhoChavePerfil];
            Criptografador cripto = new Criptografador();

            preChavePerfilDecripto = cripto.decriptografarTexto(ref chavePerfilCripto);

            arrayChaveDecripto = new BitArray(preChavePerfilDecripto);
            arrayChaveDecripto.Length = ControladorAcesso.tamanhoChavePerfil;

            arrayChaveDecripto.CopyTo(chavePerfilDecripto, 0);

            foreach (object atributo in tipoEntidadeVerificar.GetCustomAttributes(true))
                if (atributo.GetType().Name.Equals("PerfilAcesso"))
                {
                    long CodigoPerfil = long.Parse(atributo.GetType().GetField("CodigoPerfil").
                                                                      GetValue(atributo).ToString());

                    resultadoVerificacao = chavePerfilDecripto[CodigoPerfil];
                    break;
                }

            return resultadoVerificacao;
        }
        /// <summary>
        /// Serializes a BitArray into the writer.
        /// </summary>
        /// <param name="bitArray">The bit array</param>
        /// <param name="writer">The primitive writer</param>
        public static void SerializeBitArray(BitArray bitArray, IPrimitiveWriter writer)
        {
            // Write the byte length
            if (bitArray == null)
            {
                writer.Write(byte.MaxValue); // byte.MaxValue represents null
                return;
            }

            int currentByteLength = (bitArray.Count + 7) / 8;
            if (currentByteLength >= byte.MaxValue)
            {
                throw new ArgumentException("BitArray is too big to be serialized.", "bitArray");
            }
            // Write the byte length
            writer.Write((byte)currentByteLength);
            // Write only if we need to
            if (currentByteLength > 0)
            {
                // Copy the bitarray into a byte array
                byte[] bitArrayBytes = new byte[currentByteLength];
                bitArray.CopyTo(bitArrayBytes, 0);
                // Serialize
                writer.Write(bitArrayBytes);
            }
        }
Пример #11
0
 public static bool[] GetBoolArrayFromByte(byte[] bytes)
 {
     bool[] bools = new bool[bytes.Length * 8];
     BitArray bits = new BitArray(bytes);
     bits.CopyTo(bools, 0);
     return bools;
 }
Пример #12
0
 /// <summary>
 ///     将一个BitArray拼接在当前对象之后
 /// </summary>
 /// <param name="current"></param>
 /// <param name="after"></param>
 /// <returns></returns>
 public static BitArray Append(this BitArray current, BitArray after)
 {
     var bools = new bool[current.Length + after.Length];
     current.CopyTo(bools, 0);
     after.CopyTo(bools, current.Length);
     return new BitArray(bools);
 }
Пример #13
0
 /// <summary>
 ///   Get bytes bools from Boolean values.
 /// </summary>
 /// <param name = "bools">Array to be packed</param>
 /// <returns>Bytes bools</returns>
 public static byte[] GetByteArrayFromBool(bool[] bools)
 {
     BitArray bits = new BitArray(bools);
     byte[] bytes = new byte[bools.Length / 8];
     bits.CopyTo(bytes, 0);
     return bytes;
 }
Пример #14
0
        private void Setup()
        {
            // Fill Bit arrays

            chka = new[] {
                flag_0001,flag_0002,flag_0003,flag_0004,flag_0005,
                flag_2237,flag_2238,flag_2239,
                flag_0115,flag_0963, // Mewtwo
                flag_0114,flag_0790, // Zygarde
                flag_0285,flag_0286,flag_0287,flag_0288,flag_0289, // Statuettes
                flag_0290,flag_0291,flag_0292,flag_0293,flag_0294, // Super Unlocks
                flag_0675, // Chatelaine 50
                flag_2546, // Pokedex
            };
            byte[] data = new byte[0x180];
            Array.Copy(Main.SAV.Data, Main.SAV.EventFlag, data, 0, 0x180);
            BitArray BitRegion = new BitArray(data);
            BitRegion.CopyTo(flags, 0);

            // Setup Event Constant Editor
            CB_Stats.Items.Clear();
            for (int i = 0; i < Constants.Length; i += 2)
            {
                CB_Stats.Items.Add($"0x{i.ToString("X3")}");
                Constants[i / 2] = BitConverter.ToUInt16(Main.SAV.Data, Main.SAV.EventConst + i);
            }
            CB_Stats.SelectedIndex = 0;

            // Populate Flags
            setup = true;
            popFlags();
        }
Пример #15
0
 public static int GetIntegerFromBitArray(bool[] input)
 {
     var result = new int[1];
     var binary = new BitArray(input.Reverse().ToArray());
     binary.CopyTo(result, 0);
     return result[0];
 }
 private static bool[] ConvertToBitArray(int i)
 {
     BitArray b = new BitArray(new int[] { i });
       bool[] bools = new bool[b.Length];
       b.CopyTo(bools, 0);
       return bools;
 }
Пример #17
0
        private static void GoPacketGo(byte[] packet)
        {
            BitArray b = new BitArray(packet);
            b[14] = b[0];
            b[15] = b[1];
            b[22] = b[2];
            b[23] = b[3];

            b[0] = b[1] = b[2] = b[3] = false;

            b.CopyTo(packet, 0);

            MousePacket p = new MousePacket();

            p.DeltaX = 0x80 - (packet[1] ^ 0x80);
            p.DeltaY = 0x80 - (packet[2] ^ 0x80);

            //foreach (bool item in b)
            //{
            //    Console.Write(item ? '1' : '0');
            //}
            //Console.WriteLine();

            if (b[4])
                p.PressedButtons |= ButtonState.RightButton;
            if (b[5])
                p.PressedButtons |= ButtonState.LeftButton;
            if (b[29])
                p.PressedButtons |= ButtonState.MiddleButton;

            Console.WriteLine(p);
        }
Пример #18
0
 /// <summary>
 ///   Get bytes array from Boolean values.
 /// </summary>
 /// <param name = "array">Array to be packed</param>
 /// <returns>Bytes array</returns>
 public static byte[] GetByteArrayFromBool(bool[] array)
 {
     BitArray b = new BitArray(array);
     byte[] bytesArr = new byte[array.Length / 8];
     b.CopyTo(bytesArr, 0);
     return bytesArr;
 }
        private void Setup()
        {
            // Fill Bit arrays

            chka = new[] {
                flag_0001,flag_0002,flag_0003,flag_0004,flag_0005,
                flag_2237,flag_2238,flag_2239,
                flag_0115,flag_0963, // Mewtwo
                flag_0114,flag_0790, // Zygarde
                flag_0285,flag_0286,flag_0287,flag_0288,flag_0289, // Statuettes
                flag_0290,flag_0291,flag_0292,flag_0293,flag_0294, // Super Unlocks
                flag_0675, // Chatelaine 50
                flag_2546, // Pokedex
            };
            int offset = 0x1A0FC + savshift;
            byte[] data = new byte[0x180];
            Array.Copy(m_parent.savefile, offset, data, 0, 0x180);
            BitArray BitRegion = new BitArray(data);
            BitRegion.CopyTo(flags, 0);

            // Setup Event Constant Editor
            CB_Stats.Items.Clear();
            for (int i = 0; i < 0x2FC; i += 2)
            {
                CB_Stats.Items.Add(String.Format("0x{0}", i.ToString("X3")));
                Constants[i / 2] = BitConverter.ToUInt16(m_parent.savefile, 0x19E00 + i);
            }
            CB_Stats.SelectedIndex = 0;

            // Populate Flags
            setup = true;
            popFlags();
        }
Пример #20
0
        public AudioFile DecodeHiddenMessage(AudioFile containerAudioFile)
        {
            var hiddenBitsPerSample = containerAudioFile.waveFile.bitsPerSample / CHANGING_SAMPLES_FACTOR;

            var hiddenMessageBits = new BitArray((int)(containerAudioFile.waveFile.samples.Length * hiddenBitsPerSample));

            var maxNumberOfDecodingSteps = containerAudioFile.waveFile.samples.Length;

            for (int i = 0; i < maxNumberOfDecodingSteps; i++)
            {
                var uintValue = containerAudioFile.waveFile.samples[i];
                var intFromBitsToRead = uintValue.GetLastNBitsIntValue((int) hiddenBitsPerSample);

                var hiddenIntBits = new BitArray(new[] { intFromBitsToRead }).GetBitArrayFromBitArrayRange(0, (int) hiddenBitsPerSample);

                for(int j = 0; j < hiddenIntBits.Length; j++)
                {
                    hiddenMessageBits.Set(i * (int) hiddenBitsPerSample + j, hiddenIntBits[j]);
                }
            }

            containerAudioFile.waveFile.Save();

            var messageBytes = new byte[hiddenMessageBits.Count];
            hiddenMessageBits.CopyTo(messageBytes, 0);

            return new AudioFile(containerAudioFile.bytes, messageBytes);
        }
 private static int ConvertBitArrayToInt(bool[] bits)
 {
     BitArray b = new BitArray(bits);
       int[] intArr = new int[1];
       b.CopyTo(intArr, 0);
       return intArr[0];
 }
Пример #22
0
 public static bool[] ConvertByteArrayToBoolArray(byte[] bytes)
 {
     System.Collections.BitArray b = new System.Collections.BitArray(bytes);
     bool[] bitValues = new bool[b.Count];
     b.CopyTo(bitValues, 0);
     Array.Reverse(bitValues);
     return(bitValues);
 }
Пример #23
0
        public byte[] criptografarBinario(BitArray arrayBinarioCriptografar, int tamanhoArray)
        {
            byte[] arrayCriptografar = new byte[tamanhoArray];

            arrayBinarioCriptografar.CopyTo(arrayCriptografar, 0);

            return provedorCriptografia.CreateEncryptor().TransformFinalBlock(arrayCriptografar, 0, arrayCriptografar.Length);
        }
        public byte ToByte()
        {
            var bitArray = new BitArray(new bool[] { CapeEnabled, JackedEnabled, LeftSleeveEnabled, RightSleeveEnabled, LeftPantsEnabled, RightPantsEnabled, HatEnabled, Unused });
            var byteArray = new byte[1];
            bitArray.CopyTo(byteArray, 0);

            return byteArray[0];
        }
Пример #25
0
        public static UInt16 ConvertBitArrayToUInt16(BitArray bitArray)
        {
            Int32[] result = new Int32[1];

            //ReverseBitArray(ref bitArray);
            bitArray.CopyTo(result, 0);

            return (UInt16)result[0];
        }
Пример #26
0
 private uint GetIdFromBytes(byte[] bytes)
 {
     var bitArray = new BitArray(bytes);
     bitArray[31] = false;
     bitArray[30] = false;
     var idBytes = new byte[4];
     bitArray.CopyTo(idBytes, 0);
     return BitConverter.ToUInt32(idBytes, 0);
 }
Пример #27
0
        //http://stackoverflow.com/questions/5283180/how-i-can-convert-bitarray-to-single-int
        private int getIntFromBitArray(BitArray bitArray)
        {
            if (bitArray.Length > 32)
                throw new ArgumentException("Argument length shall be at most 32 bits.");

            int[] array = new int[1];
            bitArray.CopyTo(array, 0);
            return array[0];
        }
Пример #28
0
 public override void Execute()
 {
     if (!this.IsPrepared)
     {
         base.Execute();
     }
     else
     {
         MySqlStream stream = new MySqlStream(base.Driver.Encoding);
         BitArray array = new BitArray(base.Parameters.Count);
         if (this.paramList != null)
         {
             for (int i = 0; i < this.paramList.Length; i++)
             {
                 MySqlParameter parameter = base.Parameters[this.paramList[i].ColumnName];
                 if ((parameter.Value == DBNull.Value) || (parameter.Value == null))
                 {
                     array[i] = true;
                 }
             }
         }
         byte[] buffer = new byte[(base.Parameters.Count + 7) / 8];
         if (buffer.Length > 0)
         {
             array.CopyTo(buffer, 0);
         }
         stream.WriteInteger((long) this.statementId, 4);
         stream.WriteByte(0);
         stream.WriteInteger(1L, 4);
         stream.Write(buffer);
         stream.WriteByte(1);
         if (this.paramList != null)
         {
             foreach (MySqlField field in this.paramList)
             {
                 MySqlParameter parameter2 = base.Parameters[field.ColumnName];
                 stream.WriteInteger((long) parameter2.GetPSType(), 2);
             }
             foreach (MySqlField field2 in this.paramList)
             {
                 int index = base.Parameters.IndexOf(field2.ColumnName);
                 if (index == -1)
                 {
                     throw new MySqlException("Parameter '" + field2.ColumnName + "' is not defined.");
                 }
                 MySqlParameter parameter3 = base.Parameters[index];
                 if ((parameter3.Value != DBNull.Value) && (parameter3.Value != null))
                 {
                     stream.Encoding = field2.Encoding;
                     parameter3.Serialize(stream, true);
                 }
             }
         }
         this.executionCount++;
         base.Driver.ExecuteStatement(stream.InternalBuffer.ToArray());
     }
 }
Пример #29
0
 private static byte[] EncodeToBytes(this BitMatrix matrix)
 {
     BitArray bitArray = new BitArray(matrix.GetBits().ToArray());
     byte[] headerBytes = BitConverter.GetBytes(bitArray.Length);
     byte[] bytes = new byte[sizeof(int) + bitArray.Length / 8 + 1];
     headerBytes.CopyTo(bytes, 0);
     bitArray.CopyTo(bytes, headerBytes.Length);
     return bytes;
 }
Пример #30
0
        public static void readLSB(string filename, int bitCount, bool concat, bool fileout, bool cut, bool trim)
        {
            openImg(filename);

            BitArray message = new BitArray(rgbValues.Length * bitCount);
            byte[] messageBytes = new byte[message.Length / 8];

            for (int j = 0; j < bitCount; j++)
            {
                for (int i = 0; i < rgbValues.Length; i++)
                {
                    // Add the LSB to bitArray
                    message[i + (j * rgbValues.Length)] = (rgbValues[i] & (1 << j)) == 1;
                }
                //System.Windows.Forms.MessageBox.Show(j + "");
            }

            closeImg();
            bmp.Dispose();

            // Copy the bits from the image into the byte[]
            message.CopyTo(messageBytes, 0);

            DisplayOutput dispOutput = null;

            if (fileout)
            {
                dispOutput = new DisplayOutput(null, messageBytes, trim, cut);
            }
            else
            {
                // Copy the byte[] into a char[] and into a string
                char[] chars = new char[messageBytes.Length / sizeof(char)];
                Buffer.BlockCopy(messageBytes, 0, chars, 0, messageBytes.Length);
                string str = new string(chars);

                // Cut the gibberish if the user wants you to.
                if (concat)
                {
                    String tmp = "";
                    foreach (char c in str)
                    {
                        // Check if each character is in the desired ascii range
                        if (c >= 0x20 && c <= 0x7F)
                        {
                            tmp += c;
                        }
                    }
                    str = tmp;
                }

                // Show the message
                dispOutput = new DisplayOutput(str, null, false, cut);
            }
            dispOutput.Show();
        }
Пример #31
0
		public static void Encode (Stream stream, BitArray val)
		{
			byte[] buf = new byte[(int)Math.Ceiling (val.Count / 8.0f) + sizeof(short)];
			Array.Copy (Int16EncodingLE.Encode ((short)val.Length), buf, sizeof(short));
			val.CopyTo (buf, 2);
//			if (EncodingHelpers.Endian != EndianTypes.LittleEndian)
//				EncodingHelpers.ReverseBytes (buf, 2, buf.Length);
			stream.Write (buf, 0, buf.Length);

		}
Пример #32
0
 public byte convertBitArraytoByte(BitArray bits)
 {
     if (bits.Count != 8)
     {
         throw new ArgumentException("bits");
     }
     byte[] bytes = new byte[1];
     bits.CopyTo(bytes, 0);
     return bytes[0];
 }
Пример #33
0
        // ------------------------------------------------------------------------
        /// <summary>Sychnronous read digital inputs starting from a specified offset.</summary>
        /// <param name="module_nr">The position of the module.</param>
        /// <param name="offset">Starting offset for digital read command.</param>
        /// <param name="size">Number of bits to read.</param>
        /// <returns>Result of the read command as bool arrary.</returns>
        public bool[] ReadDigitalInputs(byte module_nr, ushort offset, ushort size)
        {
            byte[] values = { };
            bool[] data   = new bool[size];

            if (ValidateData(module_nr, size))
            {
                if (MDinfo[module_nr].digital_in_index != 0xFFFF)
                {
                    if (size <= dig_in_buffer.Length - (MDinfo[module_nr].digital_in_index * 8 + offset))
                    {
                        // ------------------------------------------------------------------------
                        // Request value from bus coupler
                        if (_refresh == 0)
                        {
                            // Read digital inputs, convert data to bool array
                            MBmaster.ReadDiscreteInputs(ID_value, 0, Convert.ToUInt16(MDinfo[module_nr].digital_in_index * 8 + offset), size, ref values);
                            if ((values == null) && (OnBCexception != null))
                            {
                                OnBCexception(excDataEmptyAnswer);
                            }
                            else
                            {
                                BitArray tmp1 = new System.Collections.BitArray(values);
                                bool[]   tmp2 = new bool[tmp1.Count];
                                tmp1.CopyTo(tmp2, 0);
                                Array.Copy(tmp2, 0, data, 0, size);
                            }
                        }
                        // ------------------------------------------------------------------------
                        // Request value from internal buffer
                        else
                        {
                            Array.Copy(dig_in_buffer, MDinfo[module_nr].digital_in_index * 8 + offset, data, 0, size);
                        }
                        return(data);
                    }
                    else if (OnBCexception != null)
                    {
                        OnBCexception(excDataSize);
                    }
                }
                else if (OnBCexception != null)
                {
                    OnBCexception(excNoDigInData);
                }
            }
            return(null);
        }
 static public int CopyTo(IntPtr l)
 {
     try {
         System.Collections.BitArray self = (System.Collections.BitArray)checkSelf(l);
         System.Array a1;
         checkType(l, 2, out a1);
         System.Int32 a2;
         checkType(l, 3, out a2);
         self.CopyTo(a1, a2);
         pushValue(l, true);
         return(1);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Пример #35
0
    public static byte[] BitArrayToBytes(System.Collections.BitArray bitarray)
    {
        if (bitarray.Length == 0)
        {
            throw new System.ArgumentException("must have at least length 1", "bitarray");
        }

        int num_bytes = bitarray.Length / 8;

        if (bitarray.Length % 8 != 0)
        {
            num_bytes += 1;
        }

        var bytes = new byte[num_bytes];

        bitarray.CopyTo(bytes, 0);
        return(bytes);
    }
Пример #36
0
        public static byte[] BitArrayToBytes(System.Collections.BitArray Coded1) // переводимо масив бітів в масив байтів
        {
            if (Coded1.Length == 0)
            {
                throw new System.ArgumentException("must have at least length 1", "bitarray");
            }

            int num_bytes = Coded1.Length / 8;

            if (Coded1.Length % 8 != 0)
            {
                num_bytes += 1;
            }

            var bytes = new byte[num_bytes];

            Coded1.CopyTo(bytes, 0);
            return(bytes);
        }
Пример #37
0
        // ------------------------------------------------------------------------
        // Modbus response data
        private void MBmaster_OnResponseData(ushort ID, byte unit, byte function, byte[] data)
        {
            switch (ID)
            {
            // ------------------------------------------------------------------------
            // Watchdog telegram
            case ID_watchdog:
                if ((data[0] == err_watchdog[0]) &&
                    (data[1] == err_watchdog[1]) &&
                    (RefreshTimer != null))
                {
                    RefreshTimer.Change(0, 0);
                    if (OnBCexception != null)
                    {
                        OnBCexception(excWatchdog);
                    }
                }
                break;

            // ------------------------------------------------------------------------
            // Digital input data
            case MasterBR.ID_dig_in:
                BitArray tmp_bit = new System.Collections.BitArray(data);
                tmp_bit.CopyTo(dig_in_buffer, 0);
                break;

            // ------------------------------------------------------------------------
            // Analog input data
            case MasterBR.ID_ana_in:
                int[] tmp_word;
                tmp_word = ByteArray2WordArray(data);
                tmp_word.CopyTo(ana_in_buffer, 0);
                break;
            }
            IsPending              = false;
            FrameErrorCounter      = 0;
            ConnectionErrorCounter = 0;
        }
Пример #38
0
        public string ToHex()
        {
            byte[] bytes = new byte[fp.Length / 8];
            fp.CopyTo(bytes, 0);
            //return System.Text.Encoding.ASCII.GetString(bytes);
            StringBuilder sb = new StringBuilder(bytes.Length);

            foreach (byte b in bytes)
            {
                int c    = Convert.ToInt32(b);
                int b1   = c / 16;
                int b2   = c % 16;
                int test = b1 * 16 + b2;
                if (test != c)
                {
                    System.Diagnostics.Debugger.Break();
                }
                //System.Diagnostics.Debug.WriteLine((int) 'A');
                //System.Diagnostics.Debug.WriteLine((int)'0');
                sb.Append((char)(65 + b1));
                sb.Append((char)(65 + b2));
            }
            return(sb.ToString());
        }
Пример #39
0
      } // End Read Function

      /// <summary>
      /// Write data to the Server Device.</summary>
      public bool Write(DataExtClass[] DataIn)
      {
         bool retVar = false;
         int i, j, jj, SAddress, boolReg, boolBit;
         uint intFloat;
         DAConfClass thisArea;
         var bitArray = new System.Collections.BitArray(16);
         var BitInt = new int[1];

         //If is not initialized and not connected return  error
         if (!(isInitialized && (DataIn != null)))
         {
            Status.NewStat(StatType.Bad, "Not Ready for Writing");
            return false;
         }

         //If the DataIn and Internal data doesnt have the correct amount of data areas return error.
         if (!((DataIn.Length == MasterDriverConf.NDataAreas) && (IntData.Length == MasterDriverConf.NDataAreas)))
         {
            Status.NewStat(StatType.Bad, "Data Containers Mismatch");
            return false;
         }

         if (!(isConnected && ModTCPObj.Connected))
         {
            Status.NewStat(StatType.Bad, "Connection Error...");
            this.Disconect();
            return false;
         }

         for (i = 0; i < MasterDriverConf.NDataAreas; i++)
         {
            thisArea = MasterDataAreaConf[i];
            SAddress = int.Parse(thisArea.StartAddress);

            if (thisArea.Enable && thisArea.Write)
            {
               jj = 0; //Index reinitialize

               for (j = 0; j < thisArea.Amount; j++)
               {
                  switch (thisArea.dataType)
                  {
                     case DriverConfig.DatType.Bool:
                        if (thisArea.DBnumber == 1)
                        {
                           if ((IntData[i].dBool.Length > j) && (DataIn[i].Data.dBoolean.Length > j))
                           {
                              IntData[i].dBool[j] = DataIn[i].Data.dBoolean[j];
                           }
                        }
                        else if (thisArea.DBnumber == 3)
                        {
                           boolReg = Math.DivRem(j, 16, out boolBit);
                           if ((IntData[i].dInt.Length > boolReg) && (DataIn[i].Data.dBoolean.Length > j))
                           {
                              if (boolBit == 0) { bitArray.SetAll(false); BitInt[0] = 0; }
                              bitArray.Set(boolBit, DataIn[i].Data.dBoolean[j]);
                              bitArray.CopyTo(BitInt, 0);
                              IntData[i].dInt[boolReg] = BitInt[0];
                           }
                        }
                        break;
                     case DriverConfig.DatType.Byte:
                        IntData[i].dInt[j] = DataIn[i].Data.dByte[j];
                        break;
                     case DriverConfig.DatType.Word:
                        IntData[i].dInt[j] = DataIn[i].Data.dWord[j];
                        break;
                     case DriverConfig.DatType.DWord:
                        //Endianess of the double word.
                        if (RegOrder == ModbusClient.RegisterOrder.HighLow)
                        {
                           IntData[i].dInt[jj] = (int)((DataIn[i].Data.dDWord[j] & MaskHWord) >> 16);
                           IntData[i].dInt[(jj + 1)] = (int)(DataIn[i].Data.dDWord[j] & MaskWord);
                        }
                        else
                        {
                           IntData[i].dInt[jj] = (int)(DataIn[i].Data.dDWord[j] & MaskWord);
                           IntData[i].dInt[(jj + 1)] = (int)((DataIn[i].Data.dDWord[j] & MaskHWord) >> 16);
                        }

                        jj = jj + 2;

                        break;
                     case DriverConfig.DatType.Real:
                        //Float point decimal.

                        //Convert the 
                        intFloat = (uint)Math.Abs(Math.Round(DataIn[i].Data.dReal[j] * 1000.0));

                        //Turn ON/OFF the sign bit.
                        if (DataIn[i].Data.dReal[j] < 0)
                        {
                           intFloat = intFloat | MaskNeg;
                        }
                        else
                        {
                           intFloat = intFloat & MaskiNeg;
                        }

                        //Endianess of the double word.
                        if (RegOrder == ModbusClient.RegisterOrder.HighLow)
                        {
                           IntData[i].dInt[jj] = (int)((intFloat & MaskHWord) >> 16);
                           IntData[i].dInt[(jj + 1)] = (int)(intFloat & MaskWord);
                        }
                        else
                        {
                           IntData[i].dInt[jj] = (int)(intFloat & MaskWord);
                           IntData[i].dInt[(jj + 1)] = (int)((intFloat & MaskHWord) >> 16);
                        }

                        jj = jj + 2;

                        break;
                     default:
                        Status.NewStat(StatType.Warning, "Wrong DataArea Type, Check Config.");
                        break;
                  }
               } // For j

               try
               {
                  //Write the data to the device
                  if ((thisArea.DBnumber == 1) && (thisArea.dataType == DriverConfig.DatType.Bool))
                  {
                     ModTCPObj.WriteMultipleCoils(SAddress, IntData[i].dBool);
                     retVar = true;
                  }
                  else if (thisArea.DBnumber == 3)
                  {
                     ModTCPObj.WriteMultipleRegisters(SAddress, IntData[i].dInt);
                     retVar = true;
                  }
                  else
                  {
                     retVar = false;
                     Status.NewStat(StatType.Warning, "Wrong FC for Write, Check Config.");
                  }

                  //Report Good
                  if (retVar) Status.NewStat(StatType.Good);
               }
               catch (Exception e)
               {
                  Status.NewStat(StatType.Bad, e.Message);
                  return false;
               }

            }// Area Enable

         } //For Data Areas.

         return retVar;
      }// END Write Function
Пример #40
0
    static object SafeConstants(uint id)
    {
        Dictionary <uint, object> hashTbl;

        if ((hashTbl = AppDomain.CurrentDomain.GetData("PADDINGPADDINGPADDING") as Dictionary <uint, object>) == null)
        {
            AppDomain.CurrentDomain.SetData("PADDINGPADDINGPADDING", hashTbl = new Dictionary <uint, object>());
            MemoryStream stream = new MemoryStream();
            Assembly     asm    = Assembly.GetCallingAssembly();
            using (DeflateStream str = new DeflateStream(asm.GetManifestResourceStream("PADDINGPADDINGPADDING"), CompressionMode.Decompress))
            {
                byte[] dat  = new byte[0x1000];
                int    read = str.Read(dat, 0, 0x1000);
                do
                {
                    stream.Write(dat, 0, read);
                    read = str.Read(dat, 0, 0x1000);
                }while (read != 0);
            }
            AppDomain.CurrentDomain.SetData("PADDINGPADDINGPADDINGPADDING", stream.ToArray());
        }
        object ret;
        uint   x  = (uint)new StackFrame(1).GetMethod().MetadataToken;
        uint   h  = 0x67452301 ^ x;
        uint   h1 = 0x3bd523a0;
        uint   h2 = 0x5f6f36c0;

        for (uint i = 1; i <= 64; i++)
        {
            h = (h & 0x00ffffff) << 8 | ((h & 0xff000000) >> 24);
            uint n = (h & 0xff) % 64;
            if (n >= 0 && n < 16)
            {
                h1 |= (((h & 0x0000ff00) >> 8) & ((h & 0x00ff0000) >> 16)) ^ (~h & 0x000000ff);
                h2 ^= (h * i + 1) % 16;
                h  += (h1 | h2) ^ 12345678;
            }
            else if (n >= 16 && n < 32)
            {
                h1 ^= ((h & 0x00ff00ff) << 8) ^ (((h & 0x00ffff00) >> 8) | (~h & 0x0000ffff));
                h2 += (h * i) % 32;
                h  |= (h1 + ~h2) & 12345678;
            }
            else if (n >= 32 && n < 48)
            {
                h1 += ((h & 0x000000ff) | ((h & 0x00ff0000) >> 16)) + (~h & 0x000000ff);
                h2 -= ~(h + n) % 48;
                h  ^= (h1 % h2) | 12345678;
            }
            else if (n >= 48 && n < 64)
            {
                h1 ^= (((h & 0x00ff0000) >> 16) | ~(h & 0x0000ff)) * (~h & 0x00ff0000);
                h2 += (h ^ i - 1) % n;
                h  -= ~(h1 ^ h2) + 12345678;
            }
        }
        uint pos = h ^ id;

        if (!hashTbl.TryGetValue(pos, out ret))
        {
            using (BinaryReader rdr = new BinaryReader(new MemoryStream((byte[])AppDomain.CurrentDomain.GetData("PADDINGPADDINGPADDINGPADDING"))))
            {
                rdr.BaseStream.Seek(pos, SeekOrigin.Begin);
                byte   type = rdr.ReadByte();
                byte[] f    = rdr.ReadBytes(rdr.ReadInt32());

                Random rand = new Random(12345678 ^ (int)pos);
                byte[] k    = new byte[f.Length];
                rand.NextBytes(k);
                System.Collections.BitArray arr = new System.Collections.BitArray(f);
                arr.Xor(new System.Collections.BitArray(k));
                arr.CopyTo(f, 0);

                if (type == 11)
                {
                    ret = BitConverter.ToDouble(f, 0);
                }
                else if (type == 22)
                {
                    ret = BitConverter.ToSingle(f, 0);
                }
                else if (type == 33)
                {
                    ret = BitConverter.ToInt32(f, 0);
                }
                else if (type == 44)
                {
                    ret = BitConverter.ToInt64(f, 0);
                }
                else if (type == 55)
                {
                    ret = Encoding.UTF8.GetString(f);
                }
                hashTbl[pos] = ret;
            }
        }
        return(ret);
    }