Ejemplo n.º 1
0
    // Update is called once per frame
    void Update()
    {
        if (ListenClient.ori != null && ListenClient.ori.Length > 4)
        {
            //Debug.Log (ListenClient.ori);
            string[] difPos = ListenClient.ori.Split('_');
            Debug.Log (difPos);
            string[] pos = difPos[0].Split(' ');

            double accel = double.Parse(difPos[1]);
            if (accel >= 7000 && !audio.isPlaying) {
                audio.Play ();
            }
            int button = int.Parse(difPos[2]);
            int trigger = int.Parse(difPos[3]);
            Debug.Log (button);
            b = new BitArray (new int[] { button });
            bool[] bits = new bool[32];
            if (button != 0) {
                b.CopyTo (bits, 0);

            }
            Debug.Log ("button " + bits[19]);
            if (bits [19]) {
                globalExtended = true;
            } else {
                globalExtended = false;
            }

            if (pos.Length >= 4)
            {
                Quaternion q = new Quaternion(float.Parse(pos[1]), float.Parse(pos[2]), float.Parse(pos[3]), float.Parse(pos[0]));
                //q = upInv * q;
                //q = Quaternion.Inverse(q);
                Vector3 e = q.eulerAngles;
                e.x *= -1;
                e.y *= -1;
                pivot.transform.rotation = Quaternion.Euler(e);
                //Debug.Log("transformed");
            }

        }

        if (ListenClient.pos != null && ListenClient.pos.Length > 5)
        {
            string[] strPos = ListenClient.pos.Split(';');
            for (int i = 0; i < strPos.Length; i++)
            {
                if (strPos[i].Contains("rwrist"))
                {
                    string[] headPos = strPos[i].Split(' ');
                    Debug.Log("POS: " + ListenClient.pos);
                    Debug.Log("i: " + strPos[i]);
                    transform.position =
                        new Vector3(float.Parse(headPos[1]) * 5, float.Parse(headPos[2]) * 5, 7 - float.Parse(headPos[3]) * 2);
                    break;
                }
            }
        }
    }
Ejemplo n.º 2
0
        public override void Execute()
        {
            // if we are not prepared, then call down to our base
            if (!IsPrepared)
            {
                base.Execute();
                return;
            }

            //TODO: support long data here
            // create our null bitmap

            // we check this because Mono doesn't ignore the case where nullMapBytes
            // is zero length.
            //            if (nullMapBytes.Length > 0)
            //          {
            //            byte[] bits = packet.Buffer;
            //          nullMap.CopyTo(bits,
            //        nullMap.CopyTo(nullMapBytes, 0);

            // start constructing our packet
            //            if (Parameters.Count > 0)
            //              nullMap.CopyTo(packet.Buffer, nullMapPosition);
            //if (parameters != null && parameters.Count > 0)
            //else
            //	packet.WriteByte( 0 );
            //TODO:  only send rebound if parms change

            // now write out all non-null values
            _packet.Position = _dataPosition;
            for (int i = 0; i < _parametersToSend.Count; i++)
            {
                MySqlParameter p = _parametersToSend[i];
                _nullMap[i] = (p.Value == DBNull.Value || p.Value == null) ||
                              p.Direction == ParameterDirection.Output;
                if (_nullMap[i])
                {
                    continue;
                }
                _packet.Encoding = p.Encoding;
                p.Serialize(_packet, true, Connection.Settings);
            }
            _nullMap?.CopyTo(_packet.Buffer, _nullMapPosition);

            ExecutionCount++;

            Driver.ExecuteStatement(_packet);
        }
Ejemplo n.º 3
0
 public static byte[] BitArrayToByteArray(BitArray bits)
 {
     byte[] ret = new byte[bits.Length / 8];
     bits.CopyTo(ret, 0);
     return(ret);
 }
Ejemplo n.º 4
0
        public static Byte[] GenerateStandaloneMAPForROM(ROM ROMToProcess)
        {
            Byte[] MAPBytes = new Byte[0x80];
            using (MemoryStream Mem = new MemoryStream(MAPBytes))
            {
                //Write MBC Type, ROM Size, and SRAM Size etc. for ROM
                BitArray Bits = new BitArray(16);

                //MBC Type
                if (ROMToProcess.CartridgeType >= 0x1 && ROMToProcess.CartridgeType <= 0x3)
                {
                    //MBC1
                    Bits[15] = false; Bits[14] = false; Bits[13] = true;
                }
                else if (ROMToProcess.CartridgeType >= 0x5 && ROMToProcess.CartridgeType <= 0x6)
                {
                    //MBC2
                    Bits[15] = false; Bits[14] = true; Bits[13] = false;
                }
                else if (ROMToProcess.CartridgeType >= 0xF && ROMToProcess.CartridgeType <= 0x13)
                {
                    //MBC3
                    Bits[15] = false; Bits[14] = true; Bits[13] = true;
                }
                else if (ROMToProcess.CartridgeType >= 0x19 && ROMToProcess.CartridgeType <= 0x1E)
                {
                    //MBC5
                    Bits[15] = true; Bits[14] = false; Bits[13] = true;
                }
                else
                {
                    //MBC0
                    Bits[15] = false; Bits[14] = false; Bits[13] = false;
                }

                //ROM Size
                switch (ROMToProcess.ROMSizeKByte)
                {
                case (64):
                    Bits[12] = false; Bits[11] = true; Bits[10] = false;
                    break;

                case (128):
                    Bits[12] = false; Bits[11] = true; Bits[10] = false;
                    break;

                case (256):
                    Bits[12] = false; Bits[11] = true; Bits[10] = true;
                    break;

                case (512):
                    Bits[12] = true; Bits[11] = false; Bits[10] = false;
                    break;

                case (1024):
                    Bits[12] = true; Bits[11] = false; Bits[10] = true;
                    break;
                }

                //SRAM Size
                if (ROMToProcess.RAMSizeKByte == 0)
                {
                    //No SRAM
                    Bits[9] = false; Bits[8] = false; Bits[7] = false;
                }
                else if (ROMToProcess.CartridgeType >= 0x5 && ROMToProcess.CartridgeType <= 0x6)
                {
                    //MBC2
                    Bits[9] = false; Bits[8] = false; Bits[7] = true;
                }
                else if (ROMToProcess.RAMSizeKByte == 8)
                {
                    //8KB
                    Bits[9] = false; Bits[8] = true; Bits[7] = false;
                }
                else if (ROMToProcess.RAMSizeKByte == 32)
                {
                    //32KB
                    Bits[9] = false; Bits[8] = true; Bits[7] = true;
                }
                else
                {
                    //8KB For stuff that has smaller than 8KB
                    Bits[9] = false; Bits[8] = true; Bits[7] = false;
                }

                Byte[] temp = new Byte[2];
                Bits.CopyTo(temp, 0);
                Array.Reverse(temp);
                // Or ROM Startoffset (in this case always 0x0) together with last bit of SRAM Size
                temp[1] = (byte)(0x0 | temp[1]);
                Mem.Write(temp, 0, temp.Length);

                //RAM Offset (In this case always 0x0)
                Mem.WriteByte(0x0);

                //FF Fill
                while (Mem.Position < 0x18)
                {
                    Mem.WriteByte(0xFF);
                }

                //?? Not sure what this is
                temp = new Byte[] { 0x08, 0x00, 0x40, 0x00 };
                Mem.Write(temp, 0, temp.Length);

                //Title Title ASCII "DMG -xxxx-  "
                if (!ROMToProcess.CGB)
                {
                    temp = System.Text.ASCIIEncoding.ASCII.GetBytes("DMG -A" + ROMToProcess.ASCIITitle.Substring(0, 2) + "J-  ");
                }
                else
                {
                    temp = System.Text.ASCIIEncoding.ASCII.GetBytes("CGB -A" + ROMToProcess.ASCIITitle.Substring(0, 2) + "J-  ");
                }
                Mem.Write(temp, 0, temp.Length);

                //Title SHIFT-JIS
                //temp = new Byte[] { 0x82, 0x50, 0x82, 0x54, 0x82, 0x61, 0x83, 0x7B, 0x83, 0x93, 0x83, 0x6F, 0x81, 0x5B, 0x83, 0x7D, 0x83, 0x93, 0x82, 0x66, 0x82, 0x61, 0x82, 0x52, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20 };
                Encoding ShiftJIS = Encoding.GetEncoding(932);
                String   temp1    = "これを読めば、あなたはばかだ";
                temp1 = temp1.PadRight(30, ' ');
                temp  = ShiftJIS.GetBytes(temp1);
                Mem.Write(temp, 0, temp.Length);

                //Date ASCII "MM/DD/YYYY" + Time ASCII"HH:MM:SS"
                temp1 = DateTime.Now.ToString(@"MM\/dd\/yyyyHH:mm:ss");
                temp  = System.Text.ASCIIEncoding.ASCII.GetBytes(temp1);
                Mem.Write(temp, 0, temp.Length);

                //LAW ASCII  "LAWnnnnn"
                temp = System.Text.ASCIIEncoding.ASCII.GetBytes("LAW03347");
                Mem.Write(temp, 0, temp.Length);

                //?? No idea what this does
                temp = new Byte[] { 0x01, 0x00, 0x30, 0x25, 0x00, 0x03, 0x01, 0x00, 0x12, 0x57, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00 };
                Mem.Write(temp, 0, temp.Length);
            }
            return(MAPBytes);
        }
Ejemplo n.º 5
0
 private byte[] BitArrayToByteArray(BitArray bits)
 {
     byte[] ret = new byte[(bits.Length - 1) / 8 + 1];
     bits.CopyTo(ret, 0);
     return(ret);
 }
Ejemplo n.º 6
0
        public override bool[] ToBitArray()
        {
            int num = 0;

            bool[]   bit_array = new bool[33554432];
            BitArray bitArray1 = Util.ConvertIntToBitArray((uint)this.version, 3);
            int      index1    = num + 3;

            bitArray1.CopyTo((Array)bit_array, index1);
            int index2 = index1 + 3;

            Util.ConvertIntToBitArray((uint)this.msgType, 10).CopyTo((Array)bit_array, index2);
            int index3 = index2 + 10;

            Util.ConvertIntToBitArray(this.msgLen, 32).CopyTo((Array)bit_array, index3);
            int index4 = index3 + 32;

            Util.ConvertIntToBitArray(this.msgID, 32).CopyTo((Array)bit_array, index4);
            int cursor = index4 + 32;

            try
            {
                BitArray bitArray2 = Util.ConvertObjToBitArray((object)this.AntennaID, (int)this.AntennaID_len);
                bitArray2.CopyTo((Array)bit_array, cursor);
                cursor += bitArray2.Length;
            }
            catch
            {
            }
            try
            {
                BitArray bitArray2 = Util.ConvertObjToBitArray((object)this.RequestedData, (int)this.RequestedData_len);
                bitArray2.CopyTo((Array)bit_array, cursor);
                cursor += bitArray2.Length;
            }
            catch
            {
            }
            try
            {
                BitArray bitArray2 = Util.ConvertObjToBitArray((object)this.GPIPortNum, (int)this.GPIPortNum_len);
                bitArray2.CopyTo((Array)bit_array, cursor);
                cursor += bitArray2.Length;
            }
            catch
            {
            }
            try
            {
                BitArray bitArray2 = Util.ConvertObjToBitArray((object)this.GPOPortNum, (int)this.GPOPortNum_len);
                bitArray2.CopyTo((Array)bit_array, cursor);
                cursor += bitArray2.Length;
            }
            catch
            {
            }
            if (this.Custom != null)
            {
                int length = this.Custom.Length;
                for (int index5 = 0; index5 < length; ++index5)
                {
                    this.Custom[index5].ToBitArray(ref bit_array, ref cursor);
                }
            }
            Util.ConvertIntToBitArray((uint)cursor / 8U, 32).CopyTo((Array)bit_array, 16);
            bool[] flagArray = new bool[cursor];
            Array.Copy((Array)bit_array, 0, (Array)flagArray, 0, cursor);
            return(flagArray);
        }
Ejemplo n.º 7
0
    private void GetBitrate(params bool[] fourBits)
    {
        int[] bitrateTable = GetBitrateTable();

        Array.Reverse(fourBits);
        BitArray bArray = new BitArray(fourBits);
        byte[] index = new byte[1];
        bArray.CopyTo(index, 0);

        this.bitrate = bitrateTable[index[0]];
    }
Ejemplo n.º 8
0
 static private byte BitArrayToByte(BitArray n)
 {
     byte[] _tempBA = new byte[1];
     n.CopyTo(_tempBA, 0);
     return(_tempBA[0]);
 }
Ejemplo n.º 9
0
 public static byte[] BitToByteArray(BitArray BitArrayToConvert)
 {
     byte[] ConvertedResault = new byte[(BitArrayToConvert.Length - 1) / 8 + 1];
     BitArrayToConvert.CopyTo(ConvertedResault, 0);
     return(ConvertedResault);
 }
Ejemplo n.º 10
0
Archivo: ecb.cs Proyecto: Vsio/Virulife
    /* converts binary string to binary bytes */
    public byte[] binaryStringToBytes(string _binaryString)
    {
        string binary = _binaryString;
        int i = 0;
        int j = 0;
        BitArray bits = new BitArray(8);
        byte[] bytes = new byte[binary.Length/8];

        while (j!=binary.Length) {
            for (i=0;i!=8;i++) {

                bits.Set(i,(binary[j+i]=='1'?true:false));
            }

            bits.CopyTo(bytes,j/8);
            j+=8;
        }

        return bytes;
    }
Ejemplo n.º 11
0
	// Update is called once per frame
	//void Update () {
	//}
	
		// Use this for initialization
	/*void Awake()
    {
       DontDestroyOnLoad(this);
		
		GameObject M_TC1_01 = GameObject.Find("M_TC1_01");
		GameObject M_TC1_2 = GameObject.Find("M_TC1_01");
		
    }*/
	
	private byte[] BitArrayToByteArray(BitArray bits)
	{
		
	    byte[] ret = new byte[bits.Length / 8];
	    bits.CopyTo(ret, 0);
	    return ret;
	}
Ejemplo n.º 12
0
    /*
     * Decodes received data (checks for validity, corrects network order, etc.).
     *
     * receive:	The bytes received from the server.
     * carry:	Bits that are being carried over from a previous packet.
     *
     * return:	A Decode object with decoded data or null if packet is too corrupt.
     */
    static byte[] Decode(byte[] receive)
    {
        int readcnt = 0;
        int readlen = (receive.Length-4) * 8;		// Bytes of data -> bits.
        readlen -= (readlen / 32) * 6;				// Each 32 bits has 6 parity bits.
        readlen -= (new int[] { 0, 4, 5, 5 })[receive.Length % 4];	// Parity bits for smaller packets.
        BitArray read = new BitArray(readlen);

        // Loop through each 32 bit packet after the first 32 bit header.
        for ( int i = 4; i < receive.Length; ) {
            int size = receive.Length - i;
            if ( size > 4 ) size = 4;				// Packet is between 1 and 4 bytes.

            BitArray[] data = new BitArray[size];
            for ( int e = size - 1; e >= 0; e-- )	// Copy out the bytes in reverse order.
                data[e] = Reversed(receive[i++]);	// Reverse the bits too.

            bool even;
            int badloc = -1;
            BitArray bits = Reversed(ToBits(data));	// Read in the bits.

            // Iterate through parity values (1, 2, 4, 8, ...), but skip the last parity.
            for ( int p = 1; p < bits.Length-1; p *= 2 ) {
                even = ! bits.Get(p-1);				// Even state is the opposite of the parity bit.
                // Iterate through starting points for take positions.
                for ( int l = p-1; l < bits.Length; l += p)
                    // Iterate through take values.
                    for ( int e = 0; e < p && l < bits.Length; e++, l++ )
                        // Check if take value is a parity bit.
                        if ( Math.Log(l+1, 2) % 1 != 0 )
                            even ^= bits.Get(l);	// Flip bit if 1.
                if ( ! even ) badloc += p;			// Bad bit = sum of failed parity values.
            }

            // Flip the bad bit if necessary.
            if ( badloc >= 0 ) bits.Set(badloc, ! bits.Get(badloc));

            even = true;							// Run the checksum over the full packet.
            foreach ( bool bit in bits ) even ^= bit;

            if ( ! even ) return null;				// Packet cant be fixed.

            // Extract parity bits.
            for ( int lb = bits.Length; lb > 0; lb-- )
                if ( Math.Log(lb, 2) % 1 != 0 )
                    read.Set(readcnt++, bits.Get(lb-1));
        }

        // Allocate a byte array space equal to the number of bytes read.
        byte[] bytes;
        if ( readlen % 8 == 0 )
            bytes = new byte[(readlen / 8)];
        else
            bytes = new byte[(readlen / 8) + (8 - readlen % 8)];
        read.CopyTo(bytes, 0);

        // Last block (block less than max size, 516), eliminate trailing nulls.
        if ( receive.Length < 516 ) {
            int size = bytes.Length;
            for ( ; size > 0 && bytes[size-1] == 0; size-- );
            byte[] trimmed = new byte[size];
            for ( int i = 0; i < size; i++ ) trimmed[i] = bytes[i];
            bytes = trimmed;
        }

        return bytes;
    }
Ejemplo n.º 13
0
        public void CopyTo_Invalid()
        {
            ICollection bitArray = new BitArray(10);
            // Invalid array
            Assert.Throws<ArgumentNullException>("array", () => bitArray.CopyTo(null, 0));
            Assert.Throws<ArgumentException>(null, () => bitArray.CopyTo(new long[10], 0));
            Assert.Throws<ArgumentException>(null, () => bitArray.CopyTo(new int[10, 10], 0));

            // Invalid index
            Assert.Throws<ArgumentOutOfRangeException>("index", () => bitArray.CopyTo(new byte[10], -1));
            Assert.Throws<ArgumentException>(null, () => bitArray.CopyTo(new byte[1], 2));
            Assert.Throws<ArgumentException>(null, () => bitArray.CopyTo(new bool[10], 2));
        }
        public short GetData()
        {
            //try
            //{
            BitArray ba = new BitArray(16);
            //Set all bits to 0
            ba.SetAll(false);

            /*
            Left border     00000001
            Right border    00000010
            Top border      00000100
            Bottom border   00001000
            Inside borders  00010000
            Outside borders 00100000
            Autocolor       01000000  If this bit is set, the color index in bits 12 to 15 is not used.
             */
            
            ba.Set(0, true); //this is always 0

            #region WHICH BORDERS
            if (_autocolor == true) ba.Set(1, true); 
            if (_outside == true) ba.Set(2, true);   
            if (_inside == true) ba.Set(3, true);
            if (_bottom == true) ba.Set(4, true);
            if (_top == true) ba.Set(5, true);
            if (_right == true) ba.Set(6, true);
            if (_left == true) ba.Set(7, true);
            #endregion

            #region BORDER STYLE
            /*
            0000   None
            0001   3/4 point
            0010   11/2 point
            0011   21/4 point
            0100   3 point
            0101   41/2 point
            0110   6 point
            0111   3/4 point double
            1000   11/2 point double
            1001   21/4 point double
            1010   3/4 point gray
            1011   3/4 point gray dashed
            */

            switch (_style)
            {
                case ParaBorderStyle.None:
                    ba.Set(8, false); ba.Set(9, false); ba.Set(10, false); ba.Set(11, false);
                    break;
                case ParaBorderStyle.Point3_4:
                    ba.Set(8, false); ba.Set(9, false); ba.Set(10, false); ba.Set(11, true);
                    break;
                case ParaBorderStyle.Point11_2:
                    ba.Set(8, false); ba.Set(9, false); ba.Set(10, true); ba.Set(11, false);
                    break;
                case ParaBorderStyle.Point21_4:
                    ba.Set(8, false); ba.Set(9, false); ba.Set(10, true); ba.Set(11, true);
                    break;
                case ParaBorderStyle.Point3:
                    ba.Set(8, false); ba.Set(9, true); ba.Set(10, false); ba.Set(11, false);
                    break;
                case ParaBorderStyle.Point41_2:
                    ba.Set(8, false); ba.Set(9, true); ba.Set(10, false); ba.Set(11, true);
                    break;
                case ParaBorderStyle.Point6:
                    ba.Set(8, false); ba.Set(9, true); ba.Set(10, true); ba.Set(11, false);
                    break;
                case ParaBorderStyle.PointDouble3_4:
                    ba.Set(8, false); ba.Set(9, true); ba.Set(10, true); ba.Set(11, true);
                    break;
                case ParaBorderStyle.PointDouble11_2:
                    ba.Set(8, true); ba.Set(9, false); ba.Set(10, false); ba.Set(11, false);
                    break;
                case ParaBorderStyle.PointDouble21_4:
                    ba.Set(8, true); ba.Set(9, false); ba.Set(10, false); ba.Set(11, true);
                    break;
                case ParaBorderStyle.PointGray3_4:
                    ba.Set(8, true); ba.Set(9, false); ba.Set(10, true); ba.Set(11, false);
                    break;
                case ParaBorderStyle.PointGrayDashed3_4:
                    ba.Set(8, true); ba.Set(9, false); ba.Set(10, true); ba.Set(11, true);
                    break;
                default: // no borders
                    ba.Set(8, false); ba.Set(9, false); ba.Set(10, false); ba.Set(11, false); 
                    break;
            }
            #endregion

            #region BORDER COLOR

            /*
            0000    Black
            0001    Blue
            0010    Cyan
            0011    Green
            0100    Magenta
            0101    Red
            0110    Yellow
            0111    White
            1000    DarkBlue
            1001    DarkCyan
            1010    DarkGreen
            1011    DarkMagenta
            1100    DarkRed
            1101    DarkYellow
            1110    DarkGray
            1111    LightGray
            */

            switch (_color)
            {
                case ParaBorderColor.Black:
                    ba.Set(12, false); ba.Set(13, false); ba.Set(14, false); ba.Set(15, false);
                    break;
                case ParaBorderColor.Blue:
                    ba.Set(12, false); ba.Set(13, false); ba.Set(14, false); ba.Set(15, true);
                    break;
                case ParaBorderColor.Cyan:
                    ba.Set(12, false); ba.Set(13, false); ba.Set(14, true); ba.Set(15, false);
                    break;
                case ParaBorderColor.Green:
                    ba.Set(12, false); ba.Set(13, false); ba.Set(14, true); ba.Set(15, true);
                    break;
                case ParaBorderColor.Magenta:
                    ba.Set(12, false); ba.Set(13, true); ba.Set(14, false); ba.Set(15, false);
                    break;
                case ParaBorderColor.Red:
                    ba.Set(12, false); ba.Set(13, true); ba.Set(14, false); ba.Set(15, true);
                    break;
                case ParaBorderColor.Yellow:
                    ba.Set(12, false); ba.Set(13, true); ba.Set(14, true); ba.Set(15, false);
                    break;
                case ParaBorderColor.White:
                    ba.Set(12, false); ba.Set(13, true); ba.Set(14, true); ba.Set(15, true);
                    break;
                case ParaBorderColor.DarkBlue:
                    ba.Set(12, true); ba.Set(13, false); ba.Set(14, false); ba.Set(15, false);
                    break;
                case ParaBorderColor.DarkCyan:
                    ba.Set(12, true); ba.Set(13, false); ba.Set(14, false); ba.Set(15, true);
                    break;
                case ParaBorderColor.DarkGreen:
                    ba.Set(12, true); ba.Set(13, false); ba.Set(14, true); ba.Set(15, false);
                    break;
                case ParaBorderColor.DarkMagenta:
                    ba.Set(12, true); ba.Set(13, false); ba.Set(14, true); ba.Set(15, true);
                    break;
                case ParaBorderColor.DarkRed:
                    ba.Set(12, true); ba.Set(13, true); ba.Set(14, false); ba.Set(15, false);
                    break;
                case ParaBorderColor.DarkYellow:
                    ba.Set(12, true); ba.Set(13, true); ba.Set(14, false); ba.Set(15, true);
                    break;
                case ParaBorderColor.DarkGray:
                    ba.Set(12, true); ba.Set(13, true); ba.Set(14, true); ba.Set(15, false);
                    break;
                case ParaBorderColor.LightGray:
                    ba.Set(12, true); ba.Set(13, true); ba.Set(14, true); ba.Set(15, true);
                    break;
                default:
                    ba.Set(12, false); ba.Set(13, false); ba.Set(14, false); ba.Set(15, false); //Default to Black
                    break;
            }

            #endregion

            byte[] arr = (byte[])Array.CreateInstance(typeof(byte), 2);
            
            ba.CopyTo(arr, 0);
            
            return BitConverter.ToInt16(arr, 0);            
            //}
            //catch (Exception)
            //{
            //    return 0;
            //}
        }
Ejemplo n.º 15
0
    private void GetFrequency(params bool[] twoBits)
    {
        int[] frequencyTable = GetFrequencyTable();

        Array.Reverse(twoBits);
        BitArray bArray = new BitArray(twoBits);
        byte[] index = new byte[1];
        bArray.CopyTo(index, 0);

        this.frequency = frequencyTable[index[0]];
    }
Ejemplo n.º 16
0
 public byte[] ToByteArray()
 {
     byte[] RetArray = new byte[(BitsArray.Length + 7) / 8];
     BitsArray.CopyTo(RetArray, 0);
     return(RetArray);
 }
Ejemplo n.º 17
0
 public bool runTest()
 {
     Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer);
     int iCountErrors = 0;
     int iCountTestcases = 0;
     String strLoc = "Loc_000oo";
     BitArray bitArr1;
     BitArray bitArr2;
     Boolean[] bolArr1;
     Boolean[] bolArr2;
     Byte[] bytArr1;
     Byte[] bytArr2;
     Int32[] intArr1;
     Int32[] intArr2;
     SByte[] sbtArr1;
     Int32 iNumOfElements;
     Random rnd1;
     try 
     {
         do
         {
             iNumOfElements = 10;
             rnd1 = new Random();
             strLoc = "Loc_742dsf!";
             iCountTestcases++;
             bolArr1 = new Boolean[iNumOfElements];
             for(int i=0; i<iNumOfElements; i++)
             {
                 if(rnd1.Next(10)>5)
                     bolArr1[i] = true;
                 else
                     bolArr1[i] = false;
             }
             bitArr1 = new BitArray(bolArr1);
             bolArr2 = new Boolean[iNumOfElements];
             bitArr1.CopyTo(bolArr2, 0);
             for(int i=0; i<iNumOfElements; i++)
             {
                 if(bolArr1[i] != bolArr2[i])
                 {
                     iCountErrors++;
                     Console.WriteLine("Err_753qn_" + i + "! Wrong value returned, " + bolArr1[i] + " " + bolArr1[2]);
                 }
             }
             bolArr2 = new Boolean[iNumOfElements + 20];
             bitArr1.CopyTo(bolArr2, 20);
             for(int i=0; i<iNumOfElements; i++)
             {
                 if(bolArr1[i] != bolArr2[i+20])
                 {
                     iCountErrors++;
                     Console.WriteLine("Err_763dfsf! Wrong value returned");
                 }
             }
             try
             {
                 bolArr2 = new Boolean[iNumOfElements];
                 bitArr1.CopyTo(bolArr2, 5);
                 iCountErrors++;
                 Console.WriteLine("Err_97452dsaf! No exception thrown");					
             }
             catch(ArgumentException)
             {
             }
             catch(Exception ex)
             {
                 iCountErrors++;
                 Console.WriteLine("Err_742dsf! Unexpected exception thrown, " + ex);					
             }
             try
             {
                 bolArr2 = new Boolean[iNumOfElements-1];
                 bitArr1.CopyTo(bolArr2, 0);
                 iCountErrors++;
                 Console.WriteLine("Err_97452dsaf! No exception thrown");					
             }
             catch(ArgumentException)
             {
             }
             catch(Exception ex)
             {
                 iCountErrors++;
                 Console.WriteLine("Err_753edfsf! Unexpected exception thrown, " + ex);					
             }
             try
             {
                 bolArr2 = new Boolean[iNumOfElements];
                 bitArr1.CopyTo(bolArr2, -1);
                 iCountErrors++;
                 Console.WriteLine("Err_97452dsaf! No exception thrown");					
             }
             catch(ArgumentOutOfRangeException)
             {
             }
             catch(Exception ex)
             {
                 iCountErrors++;
                 Console.WriteLine("Err_742efsg! Unexpected exception thrown, " + ex);					
             }
             try
             {
                 bolArr2 = new Boolean[iNumOfElements];
                 bitArr1.CopyTo(null, 0);
                 iCountErrors++;
                 Console.WriteLine("Err_97452dsaf! No exception thrown");					
             }
             catch(ArgumentNullException)
             {
             }
             catch(Exception ex)
             {
                 iCountErrors++;
                 Console.WriteLine("Err_10753sg! Unexpected exception thrown, " + ex);					
             }
             strLoc = "Loc_0472eaf!";
             iCountTestcases++;
             bytArr1 = new Byte[iNumOfElements];
             for(int i=0; i<iNumOfElements; i++)
             {
                 bytArr1[i] = (Byte)i;
             }
             bitArr1 = new BitArray(bytArr1);
             bytArr2 = new Byte[iNumOfElements];
             bitArr1.CopyTo(bytArr2, 0);
             for(int i=0; i<iNumOfElements; i++)
             {
                 if(bytArr1[i] != bytArr2[i])
                 {
                     iCountErrors++;
                     Console.WriteLine("Err_753qn_" + i + "! Wrong value returned, " + bolArr1[i] + " " + bolArr1[2]);
                 }
             }
             bytArr2 = new Byte[iNumOfElements + 20];
             bitArr1.CopyTo(bytArr2, 20);
             for(int i=0; i<iNumOfElements; i++)
             {
                 if(bytArr1[i] != bytArr2[i+20])
                 {
                     iCountErrors++;
                     Console.WriteLine("Err_763dfsf! Wrong value returned");
                 }
             }
             try
             {
                 bytArr2 = new Byte[iNumOfElements];
                 bitArr1.CopyTo(bytArr2, 5);
                 iCountErrors++;
                 Console.WriteLine("Err_97452dsaf! No exception thrown");					
             }
             catch(ArgumentException)
             {
             }
             catch(Exception ex)
             {
                 iCountErrors++;
                 Console.WriteLine("Err_6924qsgf! Unexpected exception thrown, " + ex);					
             }
             try
             {
                 bytArr2 = new Byte[iNumOfElements-1];
                 bitArr1.CopyTo(bytArr2, 0);
                 iCountErrors++;
                 Console.WriteLine("Err_97452dsaf! No exception thrown");					
             }
             catch(ArgumentException)
             {
             }
             catch(Exception ex)
             {
                 iCountErrors++;
                 Console.WriteLine("Err_24683rsdg! Unexpected exception thrown, " + ex);					
             }
             try
             {
                 bytArr2 = new Byte[iNumOfElements];
                 bitArr1.CopyTo(bytArr2, -1);
                 iCountErrors++;
                 Console.WriteLine("Err_97452dsaf! No exception thrown");					
             }
             catch(ArgumentOutOfRangeException)
             {
             }
             catch(Exception ex)
             {
                 iCountErrors++;
                 Console.WriteLine("Err_563twsgt! Unexpected exception thrown, " + ex);					
             }
             try
             {
                 bitArr1.CopyTo(null, 0);
                 iCountErrors++;
                 Console.WriteLine("Err_97452dsaf! No exception thrown");					
             }
             catch(ArgumentNullException)
             {
             }
             catch(Exception ex)
             {
                 iCountErrors++;
                 Console.WriteLine("Err_674tgdfgbdg! Unexpected exception thrown, " + ex);					
             }
             strLoc = "Loc_28453sf!";
             iCountTestcases++;
             intArr1 = new Int32[iNumOfElements];
             for(int i=0; i<iNumOfElements; i++)
             {
                 intArr1[i] = i;
             }
             bitArr1 = new BitArray(intArr1);
             intArr2 = new Int32[iNumOfElements];
             bitArr1.CopyTo(intArr2, 0);
             for(int i=0; i<iNumOfElements; i++)
             {
                 if(intArr1[i] != intArr2[i])
                 {
                     iCountErrors++;
                     Console.WriteLine("Err_753qn_" + i + "! Wrong value returned, " + bolArr1[i] + " " + bolArr1[2]);
                 }
             }
             intArr2 = new Int32[iNumOfElements + 20];
             bitArr1.CopyTo(intArr2, 20);
             for(int i=0; i<iNumOfElements; i++)
             {
                 if(intArr1[i] != intArr2[i+20])
                 {
                     iCountErrors++;
                     Console.WriteLine("Err_763dfsf! Wrong value returned");
                 }
             }
             try
             {
                 intArr2 = new Int32[iNumOfElements];
                 bitArr1.CopyTo(intArr2, 5);
                 iCountErrors++;
                 Console.WriteLine("Err_97452dsaf! No exception thrown");					
             }
             catch(ArgumentException)
             {
             }
             catch(Exception ex)
             {
                 iCountErrors++;
                 Console.WriteLine("Err_563rtfzgs! Unexpected exception thrown, " + ex);					
             }
             try
             {
                 intArr2 = new Int32[iNumOfElements-1];
                 bitArr1.CopyTo(intArr2, 0);
                 iCountErrors++;
                 Console.WriteLine("Err_97452dsaf! No exception thrown");					
             }
             catch(ArgumentException)
             {
             }
             catch(Exception ex)
             {
                 iCountErrors++;
                 Console.WriteLine("Err_764wdsgsf! Unexpected exception thrown, " + ex);					
             }
             try
             {
                 intArr2 = new Int32[iNumOfElements];
                 bitArr1.CopyTo(intArr2, -1);
                 iCountErrors++;
                 Console.WriteLine("Err_97452dsaf! No exception thrown");					
             }
             catch(ArgumentOutOfRangeException)
             {
             }
             catch(Exception ex)
             {
                 iCountErrors++;
                 Console.WriteLine("Err_43wsdg! Unexpected exception thrown, " + ex);					
             }
             try
             {
                 bitArr1.CopyTo(null, 0);
                 iCountErrors++;
                 Console.WriteLine("Err_97452dsaf! No exception thrown");					
             }
             catch(ArgumentNullException)
             {
             }
             catch(Exception ex)
             {
                 iCountErrors++;
                 Console.WriteLine("Err_94720dnsl! Unexpected exception thrown, " + ex);					
             }
             strLoc = "Loc_4782eaf!";
             iCountTestcases++;
             try
             {
                 sbtArr1 = new SByte[100];
                 bitArr1.CopyTo(sbtArr1, 0);
                 iCountErrors++;
                 Console.WriteLine("Err_97452dsaf! No exception thrown");					
             }
             catch(ArgumentException)
             {
             }
             catch(Exception ex)
             {
                 iCountErrors++;
                 Console.WriteLine("Err_435324sg! Unexpected exception thrown, " + ex);					
             }
             strLoc = "Loc_275sfdsgf!";
             iCountTestcases++;
             bolArr1 = new Boolean[iNumOfElements];
             for(int i=0; i<iNumOfElements; i++)
             {
                 if(rnd1.Next(10)>5)
                     bolArr1[i] = true;
                 else
                     bolArr1[i] = false;
             }
             bitArr1 = new BitArray(bolArr1);
             intArr2 = new Int32[iNumOfElements];
             try
             {
                 bitArr1.CopyTo(intArr2, 0);
             }
             catch(Exception ex)
             {
                 iCountErrors++;
                 Console.WriteLine("Err_019472eaf! Unexpected exception thrown, " + ex);					
             }
         } while (false);
     } 
     catch (Exception exc_general ) 
     {
         ++iCountErrors;
         Console.WriteLine (s_strTFAbbrev + " : Error Err_8888yyy!  strLoc=="+ strLoc +", exc_general==\n"+exc_general.ToString());
     }
     if ( iCountErrors == 0 )
     {
         Console.WriteLine( "paSs.   "+s_strTFPath +" "+s_strTFName+" ,iCountTestcases=="+iCountTestcases);
         return true;
     }
     else
     {
         Console.WriteLine("FAiL!   "+s_strTFPath+" "+s_strTFName+" ,iCountErrors=="+iCountErrors+" , BugNums?: "+s_strActiveBugNums );
         return false;
     }
 }
Ejemplo n.º 18
0
    public static void Main()
    {
        // Creates and initializes the source BitArray.
        BitArray myBA = new BitArray(4);

        myBA[0] = myBA[1] = myBA[2] = myBA[3] = true;

        // Creates and initializes the one-dimensional target Array of type Boolean.
        bool[] myBoolArray = new bool[8];
        myBoolArray[0] = false;
        myBoolArray[1] = false;

        // Displays the values of the target Array.
        Console.WriteLine("The target Boolean Array contains the following (before and after copying):");
        PrintValues(myBoolArray);

        // Copies the entire source BitArray to the target BitArray, starting at index 3.
        myBA.CopyTo(myBoolArray, 3);

        // Displays the values of the target Array.
        PrintValues(myBoolArray);

        // Creates and initializes the one-dimensional target Array of type integer.
        int[] myIntArray = new int[8];
        myIntArray[0] = 42;
        myIntArray[1] = 43;

        // Displays the values of the target Array.
        Console.WriteLine("The target integer Array contains the following (before and after copying):");
        PrintValues(myIntArray);

        // Copies the entire source BitArray to the target BitArray, starting at index 3.
        myBA.CopyTo(myIntArray, 3);

        // Displays the values of the target Array.
        PrintValues(myIntArray);

        // Creates and initializes the one-dimensional target Array of type byte.
        Array myByteArray = Array.CreateInstance(typeof(byte), 8);

        myByteArray.SetValue((byte)10, 0);
        myByteArray.SetValue((byte)11, 1);

        // Displays the values of the target Array.
        Console.WriteLine("The target byte Array contains the following (before and after copying):");
        PrintValues(myByteArray);

        // Copies the entire source BitArray to the target BitArray, starting at index 3.
        myBA.CopyTo(myByteArray, 3);

        // Displays the values of the target Array.
        PrintValues(myByteArray);

        // Returns an exception if the array is not of type Boolean, integer or byte.
        try  {
            Array myStringArray = Array.CreateInstance(typeof(String), 8);
            myStringArray.SetValue("Hello", 0);
            myStringArray.SetValue("World", 1);
            myBA.CopyTo(myStringArray, 3);
        } catch (Exception myException)  {
            Console.WriteLine("Exception: " + myException.ToString());
        }
    }
Ejemplo n.º 19
0
        // ------------------------------------------------------------------------
        // Show values in selected way
        // ------------------------------------------------------------------------
        private void ShowAs(object sender, System.EventArgs e)
        {
            RadioButton rad;

            if (sender is RadioButton)
            {
                rad = (RadioButton)sender;
                if (rad.Checked == false)
                {
                    return;
                }
            }

            bool[] bits = new bool[1];
            int[]  word = new int[1];

            // Convert data to selected data type
            if (radBits.Checked == true)
            {
                BitArray bitArray = new BitArray(data);
                bits = new bool[bitArray.Count];
                bitArray.CopyTo(bits, 0);
            }
            if (radWord.Checked == true)
            {
                if (data.Length < 2)
                {
                    return;
                }
                word = new int[data.Length / 2];
                for (int x = 0; x < data.Length; x = x + 2)
                {
                    word[x / 2] = data[x] * 256 + data[x + 1];
                }
            }

            // ------------------------------------------------------------------------
            // Put new data into text boxes
            foreach (Control ctrl in grpData.Controls)
            {
                if (ctrl is TextBox)
                {
                    int x = Convert.ToInt16(ctrl.Tag);
                    if (radBits.Checked)
                    {
                        if (x <= bits.GetUpperBound(0))
                        {
                            ctrl.Text    = Convert.ToByte(bits[x]).ToString();
                            ctrl.Visible = true;
                        }
                        else
                        {
                            ctrl.Text = "";
                        }
                    }
                    if (radBytes.Checked)
                    {
                        if (x <= data.GetUpperBound(0))
                        {
                            ctrl.Text    = data[x].ToString();
                            ctrl.Visible = true;
                        }
                        else
                        {
                            ctrl.Text = "";
                        }
                    }
                    if (radWord.Checked)
                    {
                        if (x <= word.GetUpperBound(0))
                        {
                            ctrl.Text    = word[x].ToString();
                            ctrl.Visible = true;
                        }
                        else
                        {
                            ctrl.Text = "";
                        }
                    }
                }
            }
        }
Ejemplo n.º 20
0
        /// <summary>
        /// some tests
        /// </summary>
        public static void Test()
        {
            // tests functions of BitAray which use CopyTo and expect a special order of the returned bits
            var b = new BitArray(0);

            Debug.Assert(b.Empty());
            Debug.Assert(b.All());
            Debug.Assert(b.PopulationCount() == 0);
            b.Not();
            Debug.Assert(b.Empty());
            Debug.Assert(b.All());
            Debug.Assert(b.PopulationCount() == 0);

            b = new BitArray(1);
            var ia = new Int32[1];

            b.CopyTo(ia, 0);
            Debug.Assert(ia[0] == 0);
            Debug.Assert(b.Empty());
            Debug.Assert(b.PopulationCount() == 0);
            b.Set(0, true);
            b.CopyTo(ia, 0);
            Debug.Assert(ia[0] == 1);
            Debug.Assert(b.All());
            Debug.Assert(b.PopulationCount() == 1);
            b.Not();
            Debug.Assert(b.Empty());
            Debug.Assert(b.PopulationCount() == 0);
            b.SetAll(true);
            Debug.Assert(b.All());
            Debug.Assert(b.PopulationCount() == 1);

            b = new BitArray(33);
            Debug.Assert(b.Empty());
            Debug.Assert(b.PopulationCount() == 0);
            b.Not();
            Debug.Assert(b.All());
            Debug.Assert(b.PopulationCount() == 33);

            b.Not();
            Debug.Assert(b.Empty());
            Debug.Assert(b.PopulationCount() == 0);
            for (Int32 i = 0; i < 33; i++)
            {
                b[i] = true;
            }
            Debug.Assert(b.All());
            Debug.Assert(b.PopulationCount() == 33);
            b.Not();
            Debug.Assert(b.Empty());
            Debug.Assert(b.PopulationCount() == 0);
            b.Not();
            b[32] = false;
            Debug.Assert(!b.All());
            Debug.Assert(!b.Empty());
            Debug.Assert(b.PopulationCount() == 32);

            b.Not();
            Debug.Assert(!b.All());
            Debug.Assert(!b.Empty());
            Debug.Assert(b.PopulationCount() == 1);
        }
 public static byte[] ToByteArray(BitArray bits)
 {
     byte[] ret = new byte[bits.Length / 8];
         bits.CopyTo(ret, 0);
         return ret;
 }
Ejemplo n.º 22
0
        // ------------------------------------------------------------------------
        // Read values from textboxes
        // ------------------------------------------------------------------------
        private byte[] GetData(int num)
        {
            bool[] bits = new bool[num];
            byte[] data = new Byte[num];
            int[]  word = new int[num];

            // ------------------------------------------------------------------------
            // Convert data from text boxes
            foreach (Control ctrl in grpData.Controls)
            {
                if (ctrl is TextBox)
                {
                    int x = Convert.ToInt16(ctrl.Tag);
                    if (radBits.Checked)
                    {
                        if ((x <= bits.GetUpperBound(0)) && (ctrl.Text != ""))
                        {
                            bits[x] = Convert.ToBoolean(Convert.ToByte(ctrl.Text));
                        }
                        else
                        {
                            break;
                        }
                    }
                    if (radBytes.Checked)
                    {
                        if ((x <= data.GetUpperBound(0)) && (ctrl.Text != ""))
                        {
                            data[x] = Convert.ToByte(ctrl.Text);
                        }
                        else
                        {
                            break;
                        }
                    }
                    if (radWord.Checked)
                    {
                        if ((x <= data.GetUpperBound(0)) && (ctrl.Text != ""))
                        {
                            word[x] = Convert.ToByte(ctrl.Text);
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }
            if (radBits.Checked)
            {
                int numBytes = (byte)(num / 8 + (num % 8 > 0 ? 1 : 0));
                data = new Byte[numBytes];
                BitArray bitArray = new BitArray(bits);
                bitArray.CopyTo(data, 0);
            }
            if (radWord.Checked)
            {
                data = new Byte[num * 2];
                for (int x = 0; x < num; x++)
                {
                    byte[] dat = BitConverter.GetBytes((short)IPAddress.HostToNetworkOrder((short)word[x]));
                    data[x * 2]     = dat[0];
                    data[x * 2 + 1] = dat[1];
                }
            }
            return(data);
        }
Ejemplo n.º 23
0
        private void ConfirmBtn_Click(object sender, EventArgs e)
        {
            if (NetEngine.bConnect)
            {
                //MainForm.mf.CmdWindow.Show();
                BSSParameter para = null;
                if (CurrentType)
                {
                    para = Highpara;
                }
                else
                {
                    para = Lowpara;
                }
                para.Range              = (ushort)RangeInput.Value;
                para.TvgG               = (short)TvbG.Value;
                para.PortCentralFq      = (uint)PortCentralFq.Value;
                para.StarBoardCentralFq = (uint)StartCentralFq.Value;
                para.PortBandWidth      = PortBandWidth.Value;
                para.StarBoardBandWidth = StartBandWidth.Value;
                para.Period             = (ushort)WorkPeriod.Value;
                para.Ls       = (ushort)PulseLength.Value;
                para.TVGDelay = (ushort)TVGDelay.Value;
                para.TvgAlpha = (ushort)TvgAlpha.Value;
                para.TvgBeta  = (ushort)TvgBeta.Value;
                //发射控制
                BitArray ba = new BitArray(32);
                ba[0] = PortSendEnable.Checked;
                ba[1] = StartSendEnable.Checked;
                if (PortBox.SelectedIndex == -1 || StartBox.SelectedIndex == -1)
                {
                    MessageBox.Show("请选择有效功率");
                    return;
                }
                switch (PortBox.SelectedIndex)
                {
                case 0:
                    ba[2] = true;
                    ba[3] = false;
                    ba[4] = false;
                    break;

                case 1:
                    ba[2] = false;
                    ba[3] = true;
                    ba[4] = false;
                    break;

                case 2:
                    ba[2] = true;
                    ba[3] = true;
                    ba[4] = false;
                    break;

                case 3:
                    ba[2] = false;
                    ba[3] = false;
                    ba[4] = true;
                    break;

                case 4:
                    ba[2] = true;
                    ba[3] = false;
                    ba[4] = true;
                    break;

                case 5:
                    ba[2] = false;
                    ba[3] = true;
                    ba[4] = true;
                    break;

                default:
                    ba[2] = false;
                    ba[3] = true;
                    ba[4] = true;
                    break;
                }
                switch (StartBox.SelectedIndex)
                {
                case 0:
                    ba[5] = true;
                    ba[6] = false;
                    ba[7] = false;
                    break;

                case 1:
                    ba[5] = false;
                    ba[6] = true;
                    ba[7] = false;
                    break;

                case 2:
                    ba[5] = true;
                    ba[6] = true;
                    ba[7] = false;
                    break;

                case 3:
                    ba[5] = false;
                    ba[6] = false;
                    ba[7] = true;
                    break;

                case 4:
                    ba[5] = true;
                    ba[6] = false;
                    ba[7] = true;
                    break;

                case 5:
                    ba[5] = false;
                    ba[6] = true;
                    ba[7] = true;
                    break;

                default:
                    ba[5] = false;
                    ba[6] = true;
                    ba[7] = true;
                    break;
                }
                int[] tmp = new int[1];
                ba.CopyTo(tmp, 0);
                para.Flag = (ushort)tmp[0];
                //命令标识
                if (PortFqBox.SelectedIndex == -1 || StartFqBox.SelectedIndex == -1)
                {
                    MessageBox.Show("请选择有效调频方向");
                    return;
                }
                para.ComArray[3]  = TrigerMode.Checked;
                para.ComArray[6]  = PortFqBox.SelectedIndex == 0 ? false : true;
                para.ComArray[7]  = StartFqBox.SelectedIndex == 0 ? false : true;
                para.ComArray[21] = EnablePortBSS.Checked;
                para.ComArray[22] = EnableStartBSS.Checked;
                para.ComArray[24] = CalcTVG.Checked;
                para.ComArray[25] = SingleWorkValid.Checked;
                int[] tmpcmd = new int[1];
                para.ComArray.CopyTo(tmpcmd, 0);
                para.Com = (uint)tmpcmd[0];
                if (CurrentType)
                {
                    MainForm.mf.CmdWindow.DisplayCommand("下发命令:设置高频声纳工作参数");

                    if (MainForm.mf.netcore.SendCommand(Command.SetupHighBSS(para)) == false)
                    {
                        MainForm.mf.CmdWindow.DisplayAns("下发命令不成功:" + MainForm.mf.netcore.Status);
                        MessageBox.Show("设置高频声纳工作参数失败!");
                    }
                    else
                    {
                        MessageBox.Show("设置高频声纳工作参数成功!");
                    }
                }
                else
                {
                    MainForm.mf.CmdWindow.DisplayCommand("下发命令:设置低频声纳工作参数");

                    if (MainForm.mf.netcore.SendCommand(Command.SetupLowBSS(para)) == false)
                    {
                        MainForm.mf.CmdWindow.DisplayAns("下发命令不成功:" + MainForm.mf.netcore.Status);
                        MessageBox.Show("设置低频声纳工作参数失败!");
                    }
                    else
                    {
                        MessageBox.Show("设置低频声纳工作参数成功!");
                    }
                }
                this.Hide();
            }
            else
            {
                MessageBox.Show("网络未连接,请检查网络");
            }
        }
Ejemplo n.º 24
0
        private void Setup()
        {
            // Fill Bit arrays

            chka = new[] {
                flag_0173, flag_2811, // Raikou
                flag_0174, flag_2812, // Entei
                flag_0175, flag_2813, // Suicune
                flag_0209, flag_2814, // Lugia
                flag_0208, flag_2815, // Ho-Oh
                flag_0179, flag_2816, // Uxie
                flag_0180, flag_2817, // Mesprit
                flag_0181, flag_2818, // Azelf
                flag_2819,            // Dialga
                flag_2820,            // Palkia
                flag_0260, flag_2821, // Heatran
                flag_0252, flag_2822, // Regigigas
                flag_2823,            // Giratina
                flag_0172, flag_2824, // Cresselia
                flag_0176, flag_2825, // Cobalion
                flag_0177, flag_2826, // Terrakion
                flag_0178, flag_2827, // Virizion
                flag_2828,            // Tornadus
                flag_2829,            // Thundurus
                flag_0182, flag_2830, // Reshiram
                flag_0183, flag_2831, // Zekrom
                flag_2832,            // Landorus
                flag_0184, flag_2833, // Kyurem
                flag_0419, flag_2834, // Latios
                flag_0420, flag_2835, // Latias
                flag_0956, flag_2836, // Regirock
                flag_0957, flag_2837, // Regice
                flag_0958, flag_2838, // Registeel
                flag_0648, flag_2839, // Groudon
                flag_0647, flag_2840, // Kyogre
                                      // ??????
                flag_0945, flag_2842, // Deoxys

                // Cresselia, Regigigas
                // Terrakion, Virizion

                // Maison
                flag_0284, flag_0285, flag_0286, flag_0287, flag_0288, // Statuettes
                flag_0289, flag_0290, flag_0291, flag_0292, flag_0293, // 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/2).ToString("X2")}");
                Constants[i / 2] = BitConverter.ToUInt16(Main.SAV.Data, Main.SAV.EventConst + i);
            }
            CB_Stats.SelectedIndex = 0;

            // Populate Flags
            setup = true;
            popFlags();
        }
Ejemplo n.º 25
0
 private byte[] BitToByte(BitArray bitArray)
 {
     byte[] bytes = new byte[bitArray.Length / 8];
     bitArray.CopyTo(bytes, 0);
     return(bytes);
 }
Ejemplo n.º 26
0
            /// <summary>
            /// Decodes the IR pulses according to the NEC protocol.
            /// If the train of pulses does not match the protocol, then it returns a null byte array.
            /// If the train of pulses is a repeat code, then it returns a 4-byte array with all bits set.
            /// </summary>
            /// <param name="pulses">The pulses.</param>
            /// <returns>The decoded bytes</returns>
            public static byte[] DecodePulses(InfraredPulse[] pulses)
            {
                // check if we have a repeat code
                if (IsRepeatCode(pulses))
                {
                    return new byte[] { 0xFF, 0xFF, 0xFF, 0xFF }
                }
                ;

                // from here: https://www.sbprojects.net/knowledge/ir/nec.php
                var startPulseIndex = -1;

                // The first thing we look for is the ACG (1) which should be around 9ms
                for (var pulseIndex = 0; pulseIndex < pulses.Length; pulseIndex++)
                {
                    var p = pulses[pulseIndex];
                    if (p.Value == true && p.DurationUsecs >= BurstSpaceLengthMin && p.DurationUsecs <= BurstSpaceLengthMax)
                    {
                        startPulseIndex = pulseIndex;
                        break;
                    }
                }

                // Return a null result if we could not find ACG (1)
                if (startPulseIndex == -1)
                {
                    return(null);
                }
                else
                {
                    startPulseIndex += 1;
                }

                // Find the first 0 value, 4.5 Millisecond
                for (var pulseIndex = startPulseIndex; pulseIndex < pulses.Length; pulseIndex++)
                {
                    var p = pulses[pulseIndex];
                    startPulseIndex = -1;
                    if (p.Value == false && p.DurationUsecs >= BurstMarkLengthMin && p.DurationUsecs <= BurstMarkLengthMax)
                    {
                        startPulseIndex = pulseIndex;
                        break;
                    }
                }

                // Return a null result if we could not find the start of the train of pulses
                if (startPulseIndex == -1)
                {
                    return(null);
                }
                else
                {
                    startPulseIndex += 1;
                }

                // Verify that the last pulse is a space (1) and and it is a short pulse
                var bits     = new BitArray(MaxBitLength);
                var bitCount = 0;

                var lastPulse = pulses[pulses.Length - 1];

                if (lastPulse.Value == false || lastPulse.DurationUsecs.IsBetween(ShortPulseLengthMin, ShortPulseLengthMax) == false)
                {
                    return(null);
                }

                // preallocate the pulse references
                var p1 = default(InfraredPulse);
                var p2 = default(InfraredPulse);

                // parse the bits
                for (var pulseIndex = startPulseIndex; pulseIndex < pulses.Length - 1; pulseIndex += 2)
                {
                    // logical 1 is 1 space (1) and 3 marks (0)
                    // logical 0 is 1 space (1) and 1 Mark (0)
                    p1 = pulses[pulseIndex + 0];
                    p2 = pulses[pulseIndex + 1];

                    // Expect a short Space pulse followed by a Mark pulse of variable length
                    if (p1.Value == true && p2.Value == false && p1.DurationUsecs.IsBetween(ShortPulseLengthMin, ShortPulseLengthMax))
                    {
                        bits[bitCount++] = p2.DurationUsecs.IsBetween(ShortPulseLengthMin, ShortPulseLengthMax) ? true : false;
                    }

                    if (bitCount >= MaxBitLength)
                    {
                        break;
                    }
                }

                // Check the message is 4 bytes long
                if (bitCount != 32)
                {
                    return(null);
                }

                // Return the result
                var result = new byte[bitCount / 8];

                bits.CopyTo(result, 0);
                return(result);
            }
Ejemplo n.º 27
0
 public static byte[] ConvertToByteArray(BitArray bits)
 {
     byte[] bytes = new byte[(int)Math.Ceiling(bits.Count / 8.0)];
     bits.CopyTo(bytes, 0);
     return(bytes);
 }
Ejemplo n.º 28
0
        private void setData()
        {
            // Save back the Species Bools
            // Return to Byte Array
            for (int p = 0; p < 9; p++)
            {
                byte[] sdata = new byte[0x60];

                for (int i = 0; i < 0x60 * 8; i++)
                {
                    if (specbools[p, i])
                    {
                        sdata[i / 8] |= (byte)(1 << i % 8);
                    }
                }

                sdata.CopyTo(SAV.Data, SAV.PokeDex + 8 + 0x60 * p);
            }

            // Build new bool array for the Languages
            {
                bool[] languagedata = new bool[0x280 * 8];
                for (int i = 0; i < 731; i++)
                {
                    for (int l = 0; l < 7; l++)
                    {
                        languagedata[i * 7 + l] = langbools[l, i];
                    }
                }

                // Return to Byte Array
                byte[] ldata = new byte[languagedata.Length / 8];

                for (int i = 0; i < languagedata.Length; i++)
                {
                    if (languagedata[i])
                    {
                        ldata[i / 8] |= (byte)(1 << i % 8);
                    }
                }

                ldata.CopyTo(SAV.Data, SAV.PokeDexLanguageFlags);
            }

            formbools.CopyTo(SAV.Data, SAV.PokeDex + 0x368);

            // Return Foreign Array
            {
                byte[] foreigndata = new byte[0x52];
                for (int i = 0; i < 0x52 * 8; i++)
                {
                    if (foreignbools[i])
                    {
                        foreigndata[i / 8] |= (byte)(1 << i % 8);
                    }
                }
                foreigndata.CopyTo(SAV.Data, SAV.PokeDex + 0x64C);
            }

            // Store Spinda Spot
            uint PID = Util.getHEXval(TB_Spinda.Text);

            BitConverter.GetBytes(PID).CopyTo(SAV.Data, SAV.Spinda);
        }
Ejemplo n.º 29
0
        public void SendPlayerInfo(bool sendFullUpdate)
        {
            if (connected && networkClient != null)
            {
                NetOutgoingMessage outMsg = networkClient.CreateMessage();
                outMsg.Write((byte)CommandType.UpdatePlayerInfo);
                outMsg.Write(sendFullUpdate ? (byte)1 : (byte)0);

#if DEBUG
                if (playerInfo.updateInfo.playerState == PlayerState.Game)
                {
                    List <byte> buffer = new List <byte>();

                    buffer.Add((byte)playerInfo.updateInfo.playerState);
                    buffer.AddRange(BitConverter.GetBytes(playerInfo.updateInfo.playerScore));
                    buffer.AddRange(BitConverter.GetBytes(playerInfo.updateInfo.playerCutBlocks));
                    buffer.AddRange(BitConverter.GetBytes(playerInfo.updateInfo.playerComboBlocks));
                    buffer.AddRange(BitConverter.GetBytes(playerInfo.updateInfo.playerTotalBlocks));
                    buffer.AddRange(BitConverter.GetBytes(playerInfo.updateInfo.playerEnergy));
                    buffer.AddRange(BitConverter.GetBytes(playerInfo.updateInfo.playerProgress));


                    buffer.AddRange(BitConverter.GetBytes(playerInfo.updateInfo.rightHandPos.x));
                    buffer.AddRange(BitConverter.GetBytes(playerInfo.updateInfo.rightHandPos.y));
                    buffer.AddRange(BitConverter.GetBytes(playerInfo.updateInfo.rightHandPos.z));

                    buffer.AddRange(BitConverter.GetBytes(playerInfo.updateInfo.leftHandPos.x));
                    buffer.AddRange(BitConverter.GetBytes(playerInfo.updateInfo.leftHandPos.y));
                    buffer.AddRange(BitConverter.GetBytes(playerInfo.updateInfo.leftHandPos.z));

                    buffer.AddRange(BitConverter.GetBytes(playerInfo.updateInfo.headPos.x));
                    buffer.AddRange(BitConverter.GetBytes(playerInfo.updateInfo.headPos.y));
                    buffer.AddRange(BitConverter.GetBytes(playerInfo.updateInfo.headPos.z));

                    buffer.AddRange(BitConverter.GetBytes(playerInfo.updateInfo.rightHandRot.x));
                    buffer.AddRange(BitConverter.GetBytes(playerInfo.updateInfo.rightHandRot.y));
                    buffer.AddRange(BitConverter.GetBytes(playerInfo.updateInfo.rightHandRot.z));
                    buffer.AddRange(BitConverter.GetBytes(playerInfo.updateInfo.rightHandRot.w));

                    buffer.AddRange(BitConverter.GetBytes(playerInfo.updateInfo.leftHandRot.x));
                    buffer.AddRange(BitConverter.GetBytes(playerInfo.updateInfo.leftHandRot.y));
                    buffer.AddRange(BitConverter.GetBytes(playerInfo.updateInfo.leftHandRot.z));
                    buffer.AddRange(BitConverter.GetBytes(playerInfo.updateInfo.leftHandRot.w));

                    buffer.AddRange(BitConverter.GetBytes(playerInfo.updateInfo.headRot.x));
                    buffer.AddRange(BitConverter.GetBytes(playerInfo.updateInfo.headRot.y));
                    buffer.AddRange(BitConverter.GetBytes(playerInfo.updateInfo.headRot.z));
                    buffer.AddRange(BitConverter.GetBytes(playerInfo.updateInfo.headRot.w));

                    buffer.Add((byte)playerInfo.hitsLastUpdate.Count);

                    for (int i = 0; i < (byte)playerInfo.hitsLastUpdate.Count; i++)
                    {
                        byte[] hitData = new byte[5];

                        Buffer.BlockCopy(BitConverter.GetBytes(playerInfo.hitsLastUpdate[i].objectId), 0, hitData, 0, 4);

                        BitArray bits = new BitArray(8);
                        bits[0] = playerInfo.hitsLastUpdate[i].noteWasCut;
                        bits[1] = playerInfo.hitsLastUpdate[i].isSaberA;
                        bits[2] = playerInfo.hitsLastUpdate[i].speedOK;
                        bits[3] = playerInfo.hitsLastUpdate[i].directionOK;
                        bits[4] = playerInfo.hitsLastUpdate[i].saberTypeOK;
                        bits[5] = playerInfo.hitsLastUpdate[i].wasCutTooSoon;

                        bits.CopyTo(hitData, 4);

                        buffer.AddRange(hitData);
                    }

                    buffer.InsertRange(0, BitConverter.GetBytes(buffer.Count));

                    packetsBuffer.Enqueue(buffer.ToArray());
                }
#endif
                if (sendFullUpdate)
                {
                    playerInfo.AddToMessage(outMsg);
                }
                else
                {
                    playerInfo.updateInfo.AddToMessage(outMsg);
                    outMsg.Write((byte)playerInfo.hitsLastUpdate.Count);

                    foreach (var hit in playerInfo.hitsLastUpdate)
                    {
                        hit.AddToMessage(outMsg);
                    }

                    playerInfo.hitsLastUpdate.Clear();
                }

                networkClient.SendMessage(outMsg, NetDeliveryMethod.UnreliableSequenced, 1);
            }
        }
Ejemplo n.º 30
0
    public List <string> ReadGenes()
    {
        List <string> read      = new List <string>();
        int           geneIndex = 0;

        for (int i = 0; i < startBlock.Length; i++)
        {
        }

        foreach (string[] block in startBlock)
        {
            int bitCount = 2;
            int bits     = 1;
            while (bitCount < block.Length)
            {
                bitCount *= 2;
                bits++;
            }

            BitArray bit = new BitArray(bitCount);

            for (int j = 0; j < bits; j++)
            {
                bit[j] = genes[geneIndex++];
            }

            int[] num = { 0 };

            bit.CopyTo(num, 0);

            if (num[0] >= block.Length)
            {
            }
            else
            {
                read.Add(block[num[0]]);
            }
        }
        for (int i = 0; i < numBlocks; i++)
        {
            foreach (string[] block in geneBlock)
            {
                int bitCount = 2;
                int bits     = 1;
                while (bitCount < block.Length)
                {
                    bitCount *= 2;
                    bits++;
                }

                BitArray bit = new BitArray(bitCount);

                for (int j = 0; j < bits; j++)
                {
                    bit[j] = genes[geneIndex++];
                }

                int[] num = { 0 };

                bit.CopyTo(num, 0);

                if (num[0] >= block.Length)
                {
                }
                else
                {
                    read.Add(block[num[0]]);
                }
            }
        }

        return(read);
    }
Ejemplo n.º 31
0
        private void WriteSelectedProfiles(object sender, EventArgs e)
        {
            if ((_currentConnectoinContext != null))
            {
                try {
                    if (profilesListBox.CheckedItems.Count > 0)
                    {
                        RG_ENDPOINT portEndpoin = _currentConnectoinContext.ReaderPort;
                        byte        address     = _currentConnectoinContext.ReaderAddress;

                        uint errorCode =
                            UnmanagedContext.Instance.RG_ClearProfiles(ref portEndpoin, address);
                        if (errorCode != 0)
                        {
                            throw new ApiCallException("Ошибка при очистке профилей", errorCode);
                        }

                        RG_PROFILE_DATA apiProfileData = new RG_PROFILE_DATA();
                        apiProfileData.AccessFlags = 0;
                        apiProfileData.MfKey       = new byte[6];
                        apiProfileData.MfAesKey    = new byte[16];

                        byte   profileIndex      = 0;
                        byte[] accesFlagsStorage = new byte[1];
                        foreach (var checkedProfile in profilesListBox.CheckedItems)
                        {
                            ProfileData localData = checkedProfile as ProfileData;

                            BitArray accessFlagsArray = new BitArray(8);
                            switch (localData.ProfileType)
                            {
                            case ProfileType.Mifare:
                                accessFlagsArray.Set(0, localData.CryptoOneKeyB);
                                accessFlagsArray.Set(1, localData.AesKeyB);
                                accessFlagsArray.Set(5, false);
                                accessFlagsArray.Set(6, false);
                                break;

                            case ProfileType.AppleGooglePay:
                            case ProfileType.MobileAccess:
                                accessFlagsArray.Set(0, localData.KeyBitGenerated);
                                accessFlagsArray.Set(1, localData.KeyBitDirect);
                                accessFlagsArray.Set(2, localData.KeyBitEmited);

                                accessFlagsArray.Set(5, localData.ProfileType == ProfileType.AppleGooglePay);
                                accessFlagsArray.Set(6, localData.ProfileType != ProfileType.AppleGooglePay);

                                break;
                            }
                            accessFlagsArray.CopyTo(accesFlagsStorage, 0);
                            apiProfileData.AccessFlags = accesFlagsStorage[0];

                            Buffer.BlockCopy(localData.CryptoOneKey, 0, apiProfileData.MfKey, 0,
                                             apiProfileData.MfKey.Length);
                            Buffer.BlockCopy(localData.AesKey, 0, apiProfileData.MfAesKey, 0,
                                             apiProfileData.MfAesKey.Length);

                            errorCode = UnmanagedContext.Instance.RG_WriteProfile(ref portEndpoin, address,
                                                                                  profileIndex++, localData.BlockNumber, ref apiProfileData);
                            if (errorCode != 0)
                            {
                                throw new ApiCallException("Ошибка при записи профиля.", errorCode);
                            }
                        }

                        MessageBox.Show(this, "Команда выполнена успешно.", "Сообщение", MessageBoxButtons.OK,
                                        MessageBoxIcon.Information);
                    }
                }
                catch (Exception ex) {
                    MessageBox.Show(this,
                                    string.Format("({1}) {0}", ex.Message,
                                                  (ex is ApiCallException) ? (ex as ApiCallException).ApiCallErrorCode.ToString() : "..."),
                                    "Ошибка",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
Ejemplo n.º 32
0
 public static byte[] ToByteArray(this BitArray bits)
 {
     byte[] ret = new byte[(bits.Length - 1) / 8 + 1];
     bits.CopyTo(ret, 0);
     return(ret);
 }
 public static byte ConvertByte(BitArray bits)
 {
     byte[] bytes = new byte[1];
     bits.CopyTo(bytes, 0);
     return(bytes[0]);
 }
Ejemplo n.º 34
0
        public static Byte[] GenerateMAPForMenuBinary(List <ROM> ROMList)
        {
            Byte[] MAPBytes = new Byte[0x80];
            using (MemoryStream Mem = new MemoryStream(MAPBytes))
            {
                //Write MBC Type, ROM Size, and SRAM Size for Menu
                Byte[] temp = new Byte[] { 0xA8, 0x00, 0x00 };
                Mem.Write(temp, 0, temp.Length);

                int StartOffset    = 128;
                int RAMStartOffset = 0;
                //Write MBC Type, ROM Size, and SRAM Size etc. for all ROMs
                for (int i = 0; i < ROMList.Count; i++)
                {
                    BitArray Bits = new BitArray(16);

                    //MBC Type
                    if (ROMList[i].CartridgeType >= 0x1 && ROMList[i].CartridgeType <= 0x3)
                    {
                        //MBC1
                        Bits[15] = false; Bits[14] = false; Bits[13] = true;
                    }
                    else if (ROMList[i].CartridgeType >= 0x5 && ROMList[i].CartridgeType <= 0x6)
                    {
                        //MBC2
                        Bits[15] = false; Bits[14] = true; Bits[13] = false;
                    }
                    else if (ROMList[i].CartridgeType >= 0xF && ROMList[i].CartridgeType <= 0x13)
                    {
                        //MBC3
                        Bits[15] = false; Bits[14] = true; Bits[13] = true;
                    }
                    else if (ROMList[i].CartridgeType >= 0x19 && ROMList[i].CartridgeType <= 0x1E)
                    {
                        //MBC5
                        Bits[15] = true; Bits[14] = false; Bits[13] = true;
                    }
                    else
                    {
                        //MBC0
                        Bits[15] = false; Bits[14] = false; Bits[13] = false;
                    }

                    //ROM Size
                    switch (ROMList[i].ROMSizeKByte)
                    {
                    case (64):
                        Bits[12] = false; Bits[11] = true; Bits[10] = false;
                        break;

                    case (128):
                        Bits[12] = false; Bits[11] = true; Bits[10] = false;
                        break;

                    case (256):
                        Bits[12] = false; Bits[11] = true; Bits[10] = true;
                        break;

                    case (512):
                        Bits[12] = true; Bits[11] = false; Bits[10] = false;
                        break;

                    case (1024):
                        Bits[12] = true; Bits[11] = false; Bits[10] = true;
                        break;
                    }

                    //SRAM Size
                    if (ROMList[i].RAMSizeKByte == 0)
                    {
                        //No SRAM
                        Bits[9] = false; Bits[8] = false; Bits[7] = false;
                    }
                    else if (ROMList[i].CartridgeType >= 0x5 && ROMList[i].CartridgeType <= 0x6)
                    {
                        //MBC2
                        Bits[9] = false; Bits[8] = false; Bits[7] = true;
                    }
                    else if (ROMList[i].RAMSizeKByte == 8)
                    {
                        //8KB
                        Bits[9] = false; Bits[8] = true; Bits[7] = false;
                    }
                    else if (ROMList[i].RAMSizeKByte == 32)
                    {
                        //32KB
                        Bits[9] = false; Bits[8] = true; Bits[7] = true;
                    }
                    else
                    {
                        //8KB For stuff that has smaller than 8KB
                        Bits[9] = false; Bits[8] = true; Bits[7] = false;
                    }

                    //ROM Startoffset
                    Byte StartOffsetByte = (Byte)(StartOffset / 32);
                    StartOffset += ((ROMList[i].ROMSizeKByte < 128) ? 128 : ROMList[i].ROMSizeKByte);

                    temp = new Byte[2];
                    Bits.CopyTo(temp, 0);
                    Array.Reverse(temp);
                    // Or ROM Startoffset together with last bit of SRAM Size
                    temp[1] = (byte)(StartOffsetByte | temp[1]);
                    Mem.Write(temp, 0, temp.Length);

                    //RAM Offset
                    Mem.WriteByte((Byte)(RAMStartOffset / 2));
                    RAMStartOffset += ROMList[i].RAMSizeKByte;
                }

                while (Mem.Position < 0x6E)
                {
                    Mem.WriteByte(0xFF);
                }

                //?? No idea what this does
                temp = new Byte[] { 0x02, 0x00, 0x30, 0x12, 0x99, 0x11, 0x12, 0x20, 0x37, 0x57, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00 };
                Mem.Write(temp, 0, temp.Length);
            }
            return(MAPBytes);
        }
Ejemplo n.º 35
0
        public void WriteToBinary(BinaryWriter bw)
        {
            m_HashFunction = PerfectHash.MPH.MinPerfectHash.Create(new RawStringKeySource(m_Map.Keys.ToList()), c: 1.0);
            m_HashTable    = Enumerable.Repeat <Dictionary <string, int> >(null, (int)m_HashFunction.N).ToList();

            foreach (string rawString in m_Map.Keys)
            {
                int hashCode = (int)m_HashFunction.Search(Encoding.UTF8.GetBytes(rawString));

                m_HashTable[hashCode] = m_Map[rawString];
            }

            var converter = new Utility.VietConverter();

            var uniqueAccentStrings   = new HashSet <string>();
            var uniqueAccentCodeCount = new HashSet <int>();
            int maxHashEntryCount     = 0;

            foreach (Dictionary <string, int> accCodeToCount in m_Map.Values)
            {
                foreach (string accString in accCodeToCount.Keys)
                {
                    uniqueAccentStrings.Add(accString);
                    uniqueAccentCodeCount.Add(accCodeToCount[accString]);
                }

                maxHashEntryCount = Math.Max(maxHashEntryCount, accCodeToCount.Count);
            }
            int numBitPerAccStringIndex = GetRepresentativeBitCount(uniqueAccentStrings.Count);
            int numBitPerAccCountIndex  = GetRepresentativeBitCount(uniqueAccentCodeCount.Count);
            int numBitPerHashEntryCount = GetRepresentativeBitCount(maxHashEntryCount);

            bw.Write(Version);                 // Write version number
            bw.Write(numBitPerAccStringIndex); // How many bits to represent an accent code
            bw.Write(numBitPerAccCountIndex);  // How many bits to represent an accent code's count
            bw.Write(numBitPerHashEntryCount); // How many bits to represent the count of elements in each hash entry

            var accStringList    = new List <string>();
            var accStringToIndex = new Dictionary <string, int>();
            int index            = 0;

            foreach (string accString in uniqueAccentStrings)
            {
                accStringList.Add(accString);
                accStringToIndex.Add(accString, index);
                index++;
            }
            int numBitPerAccStringLength = GetRepresentativeBitCount(accStringList.Max(s => s.Length));

            bw.Write(numBitPerAccStringLength);

            // Write ascii accent codes lookup table
            bw.Write(accStringList.Count);
            foreach (string accString in accStringList)
            {
                string asciiString = String.Join(String.Empty, accString.Select(c => (char)converter.AccentToAsciiMap[c]));
                byte[] asciiBytes  = System.Text.Encoding.ASCII.GetBytes(asciiString);

                bw.Write((byte)asciiBytes.Length);
                bw.Write(asciiBytes);
            }

            var accCodeCountList    = new List <int>();
            var accCodeCountToIndex = new Dictionary <int, int>();

            index = 0;
            foreach (int accCodeCount in uniqueAccentCodeCount)
            {
                accCodeCountList.Add(accCodeCount);
                accCodeCountToIndex.Add(accCodeCount, index);
                index++;
            }
            // Write unique accent code counts lookup table
            bw.Write(accCodeCountList.Count);
            foreach (int accCodeCount in accCodeCountList)
            {
                bw.Write(accCodeCount);
            }

            // Serialize hash function
            var hashFunctionStream = new MemoryStream();
            var formatter          = new BinaryFormatter();

            formatter.Serialize(hashFunctionStream, m_HashFunction);
            byte[] hashFunctionBytes = hashFunctionStream.ToArray();
            bw.Write(hashFunctionBytes.Length);
            bw.Write(hashFunctionBytes);

            var bitList = new List <bool>();

            foreach (var kvp in m_HashTable)
            {
                // Write number of entries, using the minimal number of bits
                int count = kvp != null ? kvp.Count : 0;

                for (int ib = numBitPerHashEntryCount - 1; ib >= 0; ib--)
                {
                    bitList.Add(((count >> ib) & 1) == 1);
                }

                if (kvp != null)
                {
                    foreach (string accString in kvp.Keys)
                    {
                        // Write accent code's index in the lookup table, using the minimal number of bits
                        for (int ib = numBitPerAccStringIndex - 1; ib >= 0; ib--)
                        {
                            bitList.Add(((accStringToIndex[accString] >> ib) & 1) == 1);
                        }

                        // Write accent code count's index in the lookup table, using the minimal number of bits
                        for (int ib = numBitPerAccCountIndex - 1; ib >= 0; ib--)
                        {
                            bitList.Add(((accCodeCountToIndex[kvp[accString]] >> ib) & 1) == 1);
                        }
                    }
                }

                // Write from queue to disk byte-aligned
                while (bitList.Count % 8 != 0)
                {
                    bitList.Add(false);
                }

                BitArray ba    = new BitArray(bitList.ToArray());
                byte[]   bytes = new byte[bitList.Count / 8];
                ba.CopyTo(bytes, 0);

                bw.Write(bytes);

                bitList.Clear();
            }
        }
Ejemplo n.º 36
0
        private void buttonandgmw_Click(object sender, EventArgs e)
        {
            string zmienna1 = comboBoxand1.SelectedItem.ToString();

            zmienna1 = zmienna1.Substring(1, 1);
            int    zm1      = Convert.ToInt32(zmienna1);
            string zmienna2 = comboBoxand2.SelectedItem.ToString();

            zmienna2 = zmienna2.Substring(1, 1);
            int zm2 = Convert.ToInt32(zmienna2);

            textBoxkonsolagmw.AppendText("x" + zm1 + " AND x" + zm2);
            textBoxkonsolagmw.AppendText(Environment.NewLine);
            int[]  bits1    = new int[Party_gmw[0].bity_x.Length];
            int[]  bits2    = new int[Party_gmw[0].bity_x.Length];
            int[]  bits_wyn = new int[Party_gmw[0].bity_x.Length];
            Random rnd      = new Random();

            foreach (Party_GMW87 P in Party_gmw)
            {
                //int bji = rnd.Next(10) % 2;
                //Console.WriteLine(bji);
                for (int i = 0; i < bits1.Length; i++)
                {
                    //int bji = rnd.Next(10) % 2;
                    bits1[i] += P.bity_udzialy[zm1, i];
                    bits2[i] += P.bity_udzialy[zm2, i];
                }
            }
            for (int i = 0; i < bits1.Length; i++)
            {
                bits1[i] = bits1[i] % 2;
                bits2[i] = bits2[i] % 2;
            }
            textBoxkonsolagmw.AppendText("zbieranie udzialow");
            textBoxkonsolagmw.AppendText(Environment.NewLine);
            textBoxkonsolagmw.AppendText("x" + zm1 + "\t\t|");
            for (int i = bits1.Length - 1; i >= 0; i--)
            {
                textBoxkonsolagmw.AppendText(bits1[i] + "|");
            }
            textBoxkonsolagmw.AppendText(Environment.NewLine);
            textBoxkonsolagmw.AppendText("x" + zm2 + "\t\t|");
            for (int i = bits2.Length - 1; i >= 0; i--)
            {
                textBoxkonsolagmw.AppendText(bits2[i] + "|");
            }
            textBoxkonsolagmw.AppendText(Environment.NewLine);
            BitArray ba_and = new BitArray(new[] { 0 });

            for (int i = 0; i < ba_and.Length; i++)
            {
                bits_wyn[i] = bits1[i] * bits2[i];
                ba_and[i]   = Convert.ToBoolean(bits_wyn[i]);
            }
            //ba_and[i] = Convert.ToBoolean(bits[i]);
            textBoxkonsolagmw.AppendText("x" + zm1 + " AND x" + zm2 + "\t|");
            for (int i = ba_and.Length - 1; i >= 0; i--)
            {
                textBoxkonsolagmw.AppendText((ba_and[i] ? 1 : 0).ToString() + "|");
            }
            textBoxkonsolagmw.AppendText(" = ");
            var result = new int[1];

            ba_and.CopyTo(result, 0);
            textBoxkonsolagmw.AppendText((result[0]).ToString());
            textBoxkonsolagmw.AppendText(Environment.NewLine);
        }
Ejemplo n.º 37
0
 public static byte[] ToBytes(this BitArray bits)
 {
     byte[] bytes = new byte[(int)Math.Ceiling(bits.Count / (double)8)];
     bits.CopyTo(bytes, 0);
     return(bytes);
 }
Ejemplo n.º 38
0
 private static byte[] getBytes(BitArray data)
 {
     byte[] bytes = new byte[data.Length / 8];
     data.CopyTo(bytes, 0);
     return(bytes);
 }
Ejemplo n.º 39
0
Archivo: Program.cs Proyecto: AyrA/R5
        private static int Split(string FileName, string DirName, int PartCount)
        {
            if (File.Exists(FileName))
            {
                FileName = Path.GetFullPath(FileName);
                var NewName = Path.GetFileName(FileName);

                if (!Directory.Exists(DirName))
                {
                    try
                    {
                        Directory.CreateDirectory(DirName);
                    }
                    catch (Exception ex)
                    {
                        Error.WriteLine("Unable to create directory. Reason: {0}", ex.Message);
                        return(RET.DIR_CREATE_ERROR);
                    }
                }
                DirName = Path.GetFullPath(DirName);
                if (PartCount > 1 && PartCount < 1000)
                {
                    using (var FS = File.OpenRead(FileName))
                    {
                        if (FS.Length <= PartCount)
                        {
                            Error.WriteLine("Part count too large for this file. Count must be less than size in bytes");
                            return(RET.INVALID_PART_COUNT);
                        }
                        long PartLength = (long)Math.Ceiling(FS.Length * 1.0 / PartCount);
                        if (PartLength > int.MaxValue)
                        {
                            throw new ArgumentOutOfRangeException("Segment length too long. Create more parts.");
                        }
                        var H = new Header()
                        {
                            Encrypted = false,
                            FileName  = Path.GetFileName(FileName),
                            FileSize  = FS.Length,
                            PartCount = PartCount
                        };
                        BitArray Parity = new BitArray(new byte[PartLength]);

                        for (var i = 1; i <= PartCount; i++)
                        {
                            H.PartNumber = i;
                            byte[] Data   = new byte[(int)PartLength];
                            int    Readed = FS.Read(Data, 0, Data.Length);
                            if (Readed > 0)
                            {
                                Parity.Xor(new BitArray(Data));
                                using (var Part = File.Create(Path.Combine(DirName, NewName + string.Format(".{0:000}", i))))
                                {
                                    H.Serialize(Part);
                                    Part.Write(Data, 0, Readed);
                                }
                            }
                            else
                            {
                                throw new IOException("Expected data but stream returned none");
                            }
                        }
                        //Write Parity
                        H.PartNumber = 0;
                        using (var Part = File.Create(Path.Combine(DirName, $"{NewName}.crc")))
                        {
                            byte[] Data = new byte[(int)PartLength];
                            Parity.CopyTo(Data, 0);
                            H.Serialize(Part);
                            Part.Write(Data, 0, Data.Length);
                        }
                    }
                }
                else
                {
                    Error.WriteLine("Invalid number of parts, expecting 2-999 but got {0}", PartCount);
                    return(RET.INVALID_PART_COUNT);
                }
            }
            else
            {
                Error.WriteLine("File not found: {0}", FileName);
                return(RET.NOT_FOUND);
            }
            return(RET.SUCCESS);
        }
Ejemplo n.º 40
0
 //    public void initzialize(int UID) {
 //        //create texture with pattern form playerprefs
 //        pattern = new Texture2D((int)pattern_size.x,(int)pattern_size.y);
 //        pattern.filterMode = FilterMode.Point;
 //        BitArray pattern_array = new BitArray(System.BitConverter.GetBytes(UID));
 //        
 //        for(int x = 0; x < pattern.width; x++){
 //            for(int y = 0; y < pattern.height; y++){
 //                    if((pattern_array[x + (y*pattern.width)])){
 //                        pattern.SetPixel(x,y,new Color32(0,0,0,0));
 //                    }
 //                    else{
 //                        pattern.SetPixel(x,y,Color.white);
 //                    }
 //            }
 //        }
 //        pattern.Apply();
 //        billboard = (GameObject)Instantiate(Resources.Load("GUI/billboard_sign"),transform.position + Vector3.up*5f,Quaternion.identity);
 //        billboard.transform.LookAt(Camera.main.transform,Vector3.up);
 //        billboard.renderer.material.SetTexture("_MainTex",pattern);
 //    }
 //    void OnGUI(){
 //        if(pattern != null){
 //            Vector3 GOSP = Camera.main.WorldToScreenPoint(gameObject.transform.position);
 //            GOSP = new Vector3(GOSP.x,Screen.height - GOSP.y,GOSP.z); //converting screenspace go "lol" GUIspace
 //            
 //            int buttonWidth = (int)(32 * Mathf.Clamp(visibilityRange - GOSP.z,0.1f,1));
 //            int buttonHeight = (int)(32 * Mathf.Clamp(visibilityRange - GOSP.z,0.1f,1));
 //            
 //            if(GOSP.z < visibilityRange && GOSP.z > 0){ //if point is within frustrum and range
 //                Graphics.DrawTexture(new Rect(GOSP.x - buttonWidth/2 + offset.x ,GOSP.y - buttonHeight/2 + offset.y, buttonWidth, buttonHeight),pattern);
 //            }
 //        }
 //    }
 private int getIntFromBitArray(BitArray bitArray)
 {
     int[] array = new int[1];
     bitArray.CopyTo(array, 0);
     return array[0];
 }
Ejemplo n.º 41
0
Archivo: Program.cs Proyecto: AyrA/R5
        private static int Join(string DirName, string FileName)
        {
            string SourceFile = null;

            //Check if directory name is a single file and adjust values as needed
            if (File.Exists(DirName))
            {
                SourceFile = Path.GetFileName(DirName);
                DirName    = Path.GetDirectoryName(DirName);
            }
            if (Directory.Exists(DirName))
            {
                var FileList = new Dictionary <string, Header>();
                if (SourceFile == null)
                {
                    Error.WriteLine("Header Collect: Auto detecting files with headers");
                    foreach (var F in Directory.EnumerateFiles(DirName))
                    {
                        var H = GetHeader(F);
                        if (H != null)
                        {
                            Error.WriteLine("Header Collect: Detected header in {0}", Path.GetFileName(F));
                            FileList.Add(F, H);
                        }
                    }
                    if (FileList.Count == 0)
                    {
                        Error.WriteLine("Header Collect: No files found with a valid header");
                        return(RET.NOT_FOUND);
                    }
                    if (!FileList.All(m => m.Value.Id == FileList.First().Value.Id))
                    {
                        Error.WriteLine("Header Collect: Multiple different headers found in the given directory. Please specify one file as input");
                        return(RET.AMBIGUOUS);
                    }
                }
                else
                {
                    var TestHeader = GetHeader(Path.Combine(DirName, SourceFile));
                    if (TestHeader == null)
                    {
                        Error.WriteLine("Header Collect: The file contains no valid header");
                        return(RET.NO_HEADER);
                    }
                    //Get all matching headers
                    foreach (var F in Directory.EnumerateFiles(DirName))
                    {
                        var H = GetHeader(F);
                        if (H != null)
                        {
                            if (H != null && H.Id == TestHeader.Id)
                            {
                                Error.WriteLine("Header Collect: Adding Header ", TestHeader.PartNumber);
                                FileList.Add(F, H);
                            }
                            else
                            {
                                Error.WriteLine("Header Collect: Ignoring header {0}", TestHeader.Id);
                            }
                        }
                    }
                }
                //TODO: Remove duplicate headers in case the user accidentally copied some header twice
                if (!ValidateHeaders(FileList.Select(m => m.Value).ToArray()))
                {
                    Error.WriteLine("Header Check: Detected duplicate/corrupt headers");
                    return(RET.INVALID_HEADER);
                }

                var HeaderList = FileList.Select(m => m.Value).OrderBy(m => m.PartNumber).ToArray();

                //Recover damaged part if needed
                if (!HasAllParts(HeaderList))
                {
                    Error.WriteLine("Join: File list has missing part");
                    if (!CanRecover(HeaderList))
                    {
                        Error.WriteLine("Join: Unable to recover. Can only recover one part, need CRC for recovery");
                        Error.WriteLine("Join: Make sure you either have all parts, or the CRC file with at most one missing part.");
                        return(RET.CANT_RECOVER);
                    }
                    using (var FS = File.Create(FileName))
                    {
                        long     PosMissing = 0;
                        var      Missing    = GetMissingId(HeaderList);
                        var      CRC        = FileList.First(m => m.Value.PartNumber == 0);
                        BitArray BA         = new BitArray(GetFileContent(CRC.Key));
                        Error.WriteLine("Join: Missing part is {0}", Missing);
                        for (var i = 1; i <= CRC.Value.PartCount; i++)
                        {
                            var Current = FileList.FirstOrDefault(m => m.Value.PartNumber == i);

                            if (i == Missing)
                            {
                                Error.WriteLine("Join Part {0}: Writing dummy segment", i);
                                //Write placeholder
                                PosMissing = FS.Position;
                                FS.Write(new byte[BA.Length / 8], 0, BA.Length / 8);
                            }
                            else
                            {
                                Error.WriteLine("Join Part {0}: Writing file segment", i);
                                var Content = GetFileContent(Current.Key);
                                FS.Write(Content, 0, Content.Length);
                                //BitArray needs equal length arrays
                                //The missing bytes are set to zero, which is the same as when we split the file
                                if (Content.Length < BA.Length / 8)
                                {
                                    Array.Resize(ref Content, BA.Length / 8);
                                }
                                BA.Xor(new BitArray(Content));
                            }
                        }
                        Error.WriteLine("Join Part {0}: Writing recovered segment", Missing);
                        FS.Flush();
                        FS.Position = PosMissing;
                        byte[] Temp = new byte[BA.Length / 8];
                        BA.CopyTo(Temp, 0);
                        FS.Write(Temp, 0, Temp.Length);

                        //Trim file if needed (might be too large if the last part was the recovered one)
                        if (FS.Position > CRC.Value.FileSize)
                        {
                            FS.Flush();
                            FS.Position = CRC.Value.FileSize;
                            FS.SetLength(CRC.Value.FileSize);
                        }

                        try
                        {
                            Error.WriteLine("Part Generator: Trying to recreate part {0}", Missing);
                            var CH = CRC.Value;
                            CH.PartNumber = Missing;
                            var NewName = Path.Combine(Path.GetDirectoryName(CRC.Key), CH.FileName) + string.Format(".{0:000}", Missing);
                            if (File.Exists(NewName))
                            {
                                throw new IOException($"{NewName} already exists");
                            }
                            using (var REC = File.Create(NewName))
                            {
                                CH.Serialize(REC);
                                REC.Write(Temp, 0, Temp.Length);
                            }
                            Error.WriteLine("Part Generator: Recreated part {0}", Missing);
                        }
                        catch (Exception ex)
                        {
                            Error.WriteLine("Part Generator: Unable to recreate part {0}", Missing);
                            Error.WriteLine("Part Generator: {0}", ex.Message);
                        }
                    }
                }
                else
                {
                    var HasCRC = FileList.Any(m => m.Value.PartNumber == 0);
                    Error.WriteLine("Join: File has all parts. Recovering normally");
                    if (!HasCRC)
                    {
                        Error.WriteLine("Join: CRC missing, will generate again");
                    }
                    //All parts here
                    var First = FileList.First(m => m.Value.PartNumber == 1).Value;
                    using (var FS = File.Create(FileName))
                    {
                        BitArray BA = null;
                        for (var i = 1; i <= First.PartCount; i++)
                        {
                            Error.WriteLine("Join Part {0}: Writing file segment", i);
                            byte[] Data = GetFileContent(FileList.First(m => m.Value.PartNumber == i).Key);
                            FS.Write(Data, 0, Data.Length);
                            if (!HasCRC)
                            {
                                if (BA == null)
                                {
                                    BA = new BitArray(Data);
                                }
                                else
                                {
                                    if (Data.Length < BA.Length / 8)
                                    {
                                        Array.Resize(ref Data, BA.Length / 8);
                                    }
                                    BA.Xor(new BitArray(Data));
                                }
                            }
                        }
                        //Trim file if needed
                        if (FS.Position > First.FileSize)
                        {
                            FS.Flush();
                            FS.Position = First.FileSize;
                            FS.SetLength(First.FileSize);
                        }
                        //Recover CRC if needed
                        if (BA != null)
                        {
                            var H = HeaderList.First();
                            //Generate part name from existing Header
                            var NewName = Path.Combine(Path.GetDirectoryName(FileName), H.FileName) + ".crc";
                            H.PartNumber = 0;
                            try
                            {
                                Error.WriteLine("Part Generator: Trying to recreate CRC");
                                if (File.Exists(NewName))
                                {
                                    throw new IOException($"{NewName} already exists");
                                }
                                using (var CRC = File.Create(NewName))
                                {
                                    H.Serialize(CRC);
                                    byte[] Data = new byte[BA.Length / 8];
                                    BA.CopyTo(Data, 0);
                                    CRC.Write(Data, 0, Data.Length);
                                }
                                Error.WriteLine("Part Generator: Recreated CRC");
                            }
                            catch (Exception ex)
                            {
                                Error.WriteLine("Part Generator: Unable to recreate CRC");
                                Error.WriteLine("Part Generator: {0}", ex.Message);
                            }
                        }
                    }
                }
            }
            else
            {
                Error.WriteLine("Header Collect: Directory not found: {0}", DirName);
                return(RET.NOT_FOUND);
            }
            return(RET.SUCCESS);
        }
Ejemplo n.º 42
0
 public bool runTest()
 {
     Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer);
     int iCountErrors = 0;
     int iCountTestcases = 0;
     String strLoc = "Loc_000oo";
     BitArray bitArr1;
     Boolean[] bolArr1;
     Boolean[] bolArr2;
     Int32 iNumOfElements;
     Random rnd1;
     try 
     {
         do
         {
             iNumOfElements = 10;
             rnd1 = new Random();
             strLoc = "Loc_742dsf!";
             iCountTestcases++;
             bolArr1 = new Boolean[iNumOfElements];
             for(int i=0; i<iNumOfElements; i++)
             {
                 if(rnd1.Next(10)>5)
                     bolArr1[i] = true;
                 else
                     bolArr1[i] = false;
             }
             bitArr1 = new BitArray(bolArr1);
             bolArr2 = new Boolean[iNumOfElements];
             bitArr1.CopyTo(bolArr2, 0);
             for(int i=0; i<iNumOfElements; i++)
             {
                 if(bolArr1[i] != bolArr2[i])
                 {
                     iCountErrors++;
                     Console.WriteLine("Err_753qn_" + i + "! Wrong value returned, " + bolArr1[i] + " " + bolArr1[2]);
                 }
             }
             if(bitArr1.IsReadOnly)
             {
                 iCountErrors++;
                 Console.WriteLine("Err_763dfsf! Wrong value returned");
             }
         } while (false);
     } 
     catch (Exception exc_general ) 
     {
         ++iCountErrors;
         Console.WriteLine (s_strTFAbbrev + " : Error Err_8888yyy!  strLoc=="+ strLoc +", exc_general==\n"+exc_general.ToString());
     }
     if ( iCountErrors == 0 )
     {
         Console.WriteLine( "paSs.   "+s_strTFPath +" "+s_strTFName+" ,iCountTestcases=="+iCountTestcases);
         return true;
     }
     else
     {
         Console.WriteLine("FAiL!   "+s_strTFPath+" "+s_strTFName+" ,iCountErrors=="+iCountErrors+" , BugNums?: "+s_strActiveBugNums );
         return false;
     }
 }
Ejemplo n.º 43
0
	public static byte[] ToByteArray(BitArray bits){
		var bytes = new byte[bits.Length / 8];
		bits.CopyTo(bytes,0);
		return bytes;
	}