GetChars() 개인적인 메소드

private GetChars ( byte bytes, int byteCount, char chars, int charCount ) : int
bytes byte
byteCount int
chars char
charCount int
리턴 int
예제 #1
0
        static public bool IsPalindrome(string s)
        {
            char[] alphabet = new char[36];

            System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();

            for (int i = 48; i < 58; i++)
            {
                byte[] byteArray = new byte[] { (byte)i };
                alphabet[i - 48] = asciiEncoding.GetChars(byteArray)[0];
            }

            for (int i = 97; i < 123; i++)
            {
                byte[] byteArray = new byte[] { (byte)i };
                alphabet[i + 10 - 97] = asciiEncoding.GetChars(byteArray)[0];
            }

            char[] c = s.ToLower().ToCharArray();

            var filer = c.Where(w => alphabet.Contains(w)).ToArray();

            for (int i = 0; i < filer.Length / 2; i++)
            {
                if (filer[i] != filer[filer.Length - 1 - i])
                {
                    return(false);
                }
            }

            return(true);
        }
예제 #2
0
    private void VerifyBytesToRead(int numBytesRead)
    {
        using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
            using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
            {
                Random rndGen       = new Random(-55);
                byte[] bytesToWrite = new byte[numRndBytesToRead];
                char[] expectedChars;
                System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();

                //Genrate random characters
                for (int i = 0; i < bytesToWrite.Length; i++)
                {
                    byte randByte = (byte)rndGen.Next(0, 256);

                    bytesToWrite[i] = randByte;
                }

                expectedChars = encoding.GetChars(bytesToWrite, 0, bytesToWrite.Length);

                Debug.WriteLine("Verifying BytesToRead with a buffer of: {0} ", numBytesRead);
                com1.Open();
                com2.Open();

                VerifyRead(com1, com2, bytesToWrite, expectedChars, numBytesRead);
            }
    }
        internal bool ContainsIllegalCharactersFilePath(string path)
        {
            // check for illegal characters
            System.Text.ASCIIEncoding AE = new System.Text.ASCIIEncoding();
            byte[] ByteArray             = { 34, 39, 60, 61, 62, 91, 92, 93, 123, 124, 125 };   // ", ', <, =, >, [, \, ], {, |, }
            char[] CharArray             = AE.GetChars(ByteArray);

            return(containsIllegalCharactersCore(CharArray, path));
        }
예제 #4
0
        /// <summary>
        /// Turn Base64 encoded text into ASCII.
        /// </summary>
        private string base64ToASCII(string text)
        {
            byte[] todecode_byte        = Convert.FromBase64String(text);
            System.Text.Decoder decoder = new System.Text.ASCIIEncoding().GetDecoder();

            int charCount = decoder.GetCharCount(todecode_byte, 0, todecode_byte.Length);

            char[] decoded_char = new char[charCount];
            decoder.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);

            return(new String(decoded_char));
        }
 static public int GetChars__A_Byte(IntPtr l)
 {
     try {
         System.Text.ASCIIEncoding self = (System.Text.ASCIIEncoding)checkSelf(l);
         System.Byte[]             a1;
         checkArray(l, 2, out a1);
         var ret = self.GetChars(a1);
         pushValue(l, true);
         pushValue(l, ret);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
예제 #6
0
        public void GetChars_Performance()
        {
            var input = new byte[2000];

            new Random().NextBytes(input);
            const int loopCount = 100000;

            var corefxAscii = new System.Text.ASCIIEncoding();
            var sshAscii    = _ascii;

            var stopWatch = new Stopwatch();

            GC.Collect();
            GC.WaitForFullGCComplete();

            stopWatch.Start();

            for (var i = 0; i < loopCount; i++)
            {
                var actual = corefxAscii.GetChars(input);
            }

            stopWatch.Stop();

            Console.WriteLine(stopWatch.ElapsedMilliseconds);

            stopWatch.Reset();

            GC.Collect();
            GC.WaitForFullGCComplete();

            stopWatch.Start();

            for (var i = 0; i < loopCount; i++)
            {
                var actual = sshAscii.GetChars(input);
            }

            stopWatch.Stop();

            Console.WriteLine(stopWatch.ElapsedMilliseconds);
        }
예제 #7
0
파일: Client.cs 프로젝트: nstcl/tcp-tftp
        public string GetFile(string filename)
        {
            byte[] rxBuf = new byte[516];
            int rxCount;
            string s = "";
            short blockNumber;
            ASCIIEncoding ae = new ASCIIEncoding();
            sendTftpPacket(Client.OP_CODE.RRQ, filename, null,-1);//send RRQ

            do
            {
                rxCount = recvTftpPacket(ref rxBuf);
                OP_CODE op = (OP_CODE)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(rxBuf, 0));
                blockNumber = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(rxBuf, 2));
                s += new string(ae.GetChars(rxBuf, sizeof(short) * 2, rxCount - 4 >= 4 ? rxCount - 4 : 0)); ;
                sendTftpPacket(Client.OP_CODE.ACK, string.Empty, null, blockNumber);
            } while (rxCount >= 516);
            //sendTftpPacket(Client.OP_CODE.ACK, string.Empty, null, blockNumber);//final ACK
            return s;
        }
예제 #8
0
    private void VerifyBytesToRead(int numBytesRead, int numNewLines)
    {
        using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
            using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
            {
                Random rndGen       = new Random(-55);
                byte[] bytesToWrite = new byte[numBytesRead + 1]; //Plus one to accomidate the NewLineByte
                System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();

                //Genrate random characters
                for (int i = 0; i < numBytesRead; i++)
                {
                    byte randByte = (byte)rndGen.Next(0, 256);

                    bytesToWrite[i] = randByte;
                }

                char[] expectedChars = encoding.GetChars(bytesToWrite, 0, bytesToWrite.Length);
                for (int i = 0; i < numNewLines; i++)
                {
                    int newLineIndex;

                    newLineIndex = rndGen.Next(0, numBytesRead);
                    bytesToWrite[newLineIndex]  = (byte)'\n';
                    expectedChars[newLineIndex] = (char)'\n';
                }

                Debug.WriteLine("Verifying BytesToRead with a buffer of: {0} ", numBytesRead);

                com1.Open();
                com2.Open();

                bytesToWrite[numBytesRead]  = DEFAULT_NEW_LINE;
                expectedChars[numBytesRead] = (char)DEFAULT_NEW_LINE;

                VerifyRead(com1, com2, bytesToWrite, expectedChars);
            }
    }
 static public int GetChars__A_Byte__Int32__Int32__A_Char__Int32(IntPtr l)
 {
     try {
         System.Text.ASCIIEncoding self = (System.Text.ASCIIEncoding)checkSelf(l);
         System.Byte[]             a1;
         checkArray(l, 2, out a1);
         System.Int32 a2;
         checkType(l, 3, out a2);
         System.Int32 a3;
         checkType(l, 4, out a3);
         System.Char[] a4;
         checkArray(l, 5, out a4);
         System.Int32 a5;
         checkType(l, 6, out a5);
         var ret = self.GetChars(a1, a2, a3, a4, a5);
         pushValue(l, true);
         pushValue(l, ret);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
예제 #10
0
 public ASCIICon(byte[] array)
 {
     ASCIIEncoding encoding = new ASCIIEncoding();
     multiString = encoding.GetChars(array);
 }
예제 #11
0
            /// <summary>Initializes the MPI environment.</summary>
        /// <param name="args">
        ///   Arguments passed to the <c>Main</c> function in your program. MPI 
        ///   may use some of these arguments for its initialization, and will remove 
        ///   them from this argument before returning.
        /// </param>
        /// <param name="threading">
        ///   The level of threading support requested of the MPI implementation. The
        ///   implementation will attempt to provide this level of threading support.
        ///   However, the actual level of threading support provided will be published
        ///   via the <see cref="MPI.Environment.Threading"/> property.
        /// </param>
        /// <remarks>
        ///   This routine must be invoked before using any other MPI facilities. 
        ///   Be sure to call <c>Dispose()</c> to finalize the MPI environment before exiting!
        /// </remarks>
        /// <example>This simple program initializes MPI and writes out the rank of each processor:
        /// <code>
        /// using MPI;
        /// 
        /// public class Hello 
        /// {
        ///     static void Main(string[] args)
        ///     {
        ///         using (MPI.Environment env = new MPI.Environment(ref args))
        ///         {
        ///             System.Console.WriteLine("Hello, from process number " 
        ///                 + MPI.Communicator.world.Rank.ToString() + " of "
        ///                 + MPI.Communicator.world.Size.ToString());
        ///         }
        ///     }
        /// }
        /// </code>
        /// </example>
        public Environment(ref string[] args, Threading threading)
        {
            if (!Initialized)
            {
                int requiredThreadLevel = 0;
                int providedThreadLevel;

                switch (threading)
                {
                    case Threading.Single:
                        requiredThreadLevel = Unsafe.MPI_THREAD_SINGLE;
                        break;
                    case Threading.Funneled:
                        requiredThreadLevel = Unsafe.MPI_THREAD_FUNNELED;
                        break;
                    case Threading.Serialized:
                        requiredThreadLevel = Unsafe.MPI_THREAD_SERIALIZED;
                        break;
                    case Threading.Multiple:
                        requiredThreadLevel = Unsafe.MPI_THREAD_MULTIPLE;
                        break;
                }

                if (args == null)
                {
                    unsafe
                    {
                        int argc = 0;
                        byte** argv = null;
                        Unsafe.MPI_Init_thread(ref argc, ref argv, requiredThreadLevel, out providedThreadLevel);
                    }
                }
                else
                {
                    ASCIIEncoding ascii = new ASCIIEncoding();
                    unsafe
                    {
                        // Copy args into C-style argc/argv
                        int my_argc = args.Length;
                        byte** my_argv = stackalloc byte*[my_argc];
                        for (int argidx = 0; argidx < my_argc; ++argidx)
                        {
                            // Copy argument into a byte array (C-style characters)
                            char[] arg = args[argidx].ToCharArray();
                            fixed (char* argp = arg)
                            {
                                int length = ascii.GetByteCount(arg);
                                byte* c_arg = stackalloc byte[length];
                                if (length > 0)
                                {
                                    ascii.GetBytes(argp, arg.Length, c_arg, length);
                                }
                                my_argv[argidx] = c_arg;
                            }
                        }

                        // Initialize MPI
                        int mpi_argc = my_argc;
                        byte** mpi_argv = my_argv;
                        Unsafe.MPI_Init_thread(ref mpi_argc, ref mpi_argv, requiredThreadLevel, out providedThreadLevel);

                        // \todo Copy c-style argc/argv back into args
                        if (mpi_argc != my_argc || mpi_argv != my_argv)
                        {
                            args = new string[mpi_argc];
                            for (int argidx = 0; argidx < args.Length; ++argidx)
                            {
                                // Find the end of the string
                                int byteCount = 0;
                                while (mpi_argv[argidx][byteCount] != 0)
                                    ++byteCount;

                                // Determine how many Unicode characters we need
                                int charCount = ascii.GetCharCount(mpi_argv[argidx], byteCount);

                                // Convert ASCII characters into unicode characters
                                char[] chars = new char[charCount];
                                fixed (char* argp = chars)
                                {
                                    ascii.GetChars(mpi_argv[argidx], byteCount, argp, charCount);
                                }

                                // Create the resulting string
                                args[argidx] = new string(chars);
                            }
                        }
                    }
                }

                switch (providedThreadLevel)
                {
                    case Unsafe.MPI_THREAD_SINGLE:
                        Environment.providedThreadLevel = Threading.Single;
                        break;
                    case Unsafe.MPI_THREAD_FUNNELED:
                        Environment.providedThreadLevel = Threading.Funneled;
                        break;
                    case Unsafe.MPI_THREAD_SERIALIZED:
                        Environment.providedThreadLevel = Threading.Serialized;
                        break;
                    case Unsafe.MPI_THREAD_MULTIPLE:
                        Environment.providedThreadLevel = Threading.Multiple;
                        break;
                    default:
                        throw new ApplicationException("MPI.NET: Underlying MPI library returned incorrect value for thread level");
                }

                // Setup communicators
                Communicator.world = Intracommunicator.Adopt(Unsafe.MPI_COMM_WORLD);
                Communicator.self = Intracommunicator.Adopt(Unsafe.MPI_COMM_SELF);
            }
        }
예제 #12
0
 /// <summary>
 /// Преобразование массива байт в массив ASCII символов
 /// </summary>
 /// <param name="byteArray"></param>
 /// <returns></returns>
 public static char[] GetChars(byte[] byteArray)
 {
     System.Text.ASCIIEncoding ASCII = new System.Text.ASCIIEncoding();
     return(ASCII.GetChars(byteArray));
 }
예제 #13
0
        public void SaveData()
        {
            //logplotDataSet1.configurationDataTable cdt = configurationTableAdapter.GetData();
            logplotDataSet1.configuration.Rows[0][1] = TOP.ToString();
            logplotDataSet1.configuration.Rows[1][1] = BASE.ToString();
            logplotDataSet1.configuration.Rows[2][1] = WIDTH.ToString();
            logplotDataSet1.configuration.Rows[3][1] = AUTHOR.ToString();
            XmlSerializer ser = new XmlSerializer(header.GetType());
            StringBuilder sb = new StringBuilder();
            TextWriter writer = new StringWriter(sb);
            ser.Serialize(writer, header);
            logplotDataSet1.configuration.Rows[4][1] = sb.ToString();
            ser = new XmlSerializer(footer.GetType());
            sb = new StringBuilder();
            writer = new StringWriter(sb);
            ser.Serialize(writer, footer);
            logplotDataSet1.configuration.Rows[5][1] = sb.ToString();
            logplotDataSet1.configuration.Rows[6][1] = Calibration.ToString();
            //            logplotDataSet1.configuration.AcceptChanges();
            this.configurationTableAdapter.Update(logplotDataSet1.configuration);

            for (int i = 0; i <= count; i++)
                if (u[i] != null)
                    try
                    {
                        logplotDataSet1.entityDataTable dt = entityTableAdapter.GetData();
                        logplotDataSet1.entityRow[] dtr = (logplotDataSet1.entityRow[])dt.Select("id=" + u[i].entity.ToString());
                        logplotDataSet1.entityRow dr = dtr[0]; //.Rows[i];
                        dr.column = i;
                        dr.name = u[i].Name;
                        XmlSerializer mySerializer = new XmlSerializer(u[i].GetType());
                        MemoryStream ms = new MemoryStream();
                        mySerializer.Serialize(ms, u[i]);
                        byte[] bs = new byte[ms.Length];
                        ms.Position = 0;
                        ms.Read(bs, 0, (int)ms.Length);
                        ASCIIEncoding a = new ASCIIEncoding();
                        String msb = new String(a.GetChars(bs));
                        dr.savedata = Convert.ToString(msb);
                        dr.type = (short)u[i].Type;

                        this.entityTableAdapter.Update(dr);

                        /*
                        logplotDataSet1.entityRow dr = (logplotDataSet1.entityRow)dt.Rows[i];
                        dr.column = i;
                        dr.name = u[i].Name;
                        XmlSerializer mySerializer = new XmlSerializer(u[i].GetType());
                        StringBuilder msb = new StringBuilder();
                        TextWriter mwriter = new StringWriter(msb);
                        mySerializer.Serialize(mwriter, u[i]);
                        dr.savedata = mwriter.ToString();
                         */
                    }
                    catch (Exception exc)
                    {
                        using (StreamWriter sw = new StreamWriter("TestFile.txt"))
                        {
                            // Add some text to the file.
                            sw.Write("This is the ");
                            sw.WriteLine("header for the file.");
                            sw.WriteLine("-------------------");
                            // Arbitrary objects can also be written to the file.
                            sw.Write(exc.Message);
                            sw.Write(exc.StackTrace);
                            sw.Write(exc.Source);
                            sw.Write(exc.ToString());
                            sw.Write("The date is: ");
                            sw.WriteLine(DateTime.Now);
                            sw.Close();
                        }
                    }

            this.tadpoleTableAdapter.Update(this.logplotDataSet1.tadpole);
            this.wellTableAdapter.Update(this.logplotDataSet1.well);
            this.percentTableAdapter.Update(this.logplotDataSet1.percent);

            this.lithologyTableAdapter.Update(this.logplotDataSet1.lithology);
            this.crossplotTableAdapter.Update(this.logplotDataSet1.crossplot);
            this.bitmapTableAdapter.Update(this.logplotDataSet1.bitmap);
            this.textTableAdapter.Update(this.logplotDataSet1.text);
            this.symbolTableAdapter.Update(this.logplotDataSet1.symbol);
            this.horizontalTableAdapter.Update(this.logplotDataSet1.horizontal);
            this.fillTableAdapter.Update(this.logplotDataSet1.fill);
            this.curveTableAdapter.Update(this.logplotDataSet1.curve);
            this.histogramTableAdapter.Update(this.logplotDataSet1.histogram);
            this.fossilTableAdapter.Update(this.logplotDataSet1.fossil);
            this.seaTableAdapter.Update(this.logplotDataSet1.sea);
            this.messageTableAdapter.Update(this.logplotDataSet1.message);
        }
예제 #14
0
        internal static ObjectManager.StaticObject ReadObject(string FileName, Encoding Encoding)
        {
            rootMatrix    = Matrix4D.NoTransformation;
            currentFolder = System.IO.Path.GetDirectoryName(FileName);
            currentFile   = FileName;
            byte[] Data = System.IO.File.ReadAllBytes(FileName);
            if (Data.Length < 16 || Data[0] != 120 | Data[1] != 111 | Data[2] != 102 | Data[3] != 32)
            {
                // not an x object
                Interface.AddMessage(MessageType.Error, false, "Invalid X object file encountered in " + FileName);
                return(null);
            }

            if (Data[4] != 48 | Data[5] != 51 | Data[6] != 48 | Data[7] != 50 & Data[7] != 51)
            {
                // unrecognized version
                System.Text.ASCIIEncoding Ascii = new System.Text.ASCIIEncoding();
                string s = new string(Ascii.GetChars(Data, 4, 4));
                Interface.AddMessage(MessageType.Error, false, "Unsupported X object file version " + s + " encountered in " + FileName);
            }

            // floating-point format
            int FloatingPointSize;

            if (Data[12] == 48 & Data[13] == 48 & Data[14] == 51 & Data[15] == 50)
            {
                FloatingPointSize = 32;
            }
            else if (Data[12] == 48 & Data[13] == 48 & Data[14] == 54 & Data[15] == 52)
            {
                FloatingPointSize = 64;
            }
            else
            {
                Interface.AddMessage(MessageType.Error, false, "Unsupported floating point format encountered in X object file " + FileName);
                return(null);
            }

            // supported floating point format
            if (Data[8] == 116 & Data[9] == 120 & Data[10] == 116 & Data[11] == 32)
            {
                // textual flavor
                string[] Lines = File.ReadAllLines(FileName, Encoding);
                // strip away comments
                bool Quote = false;
                for (int i = 0; i < Lines.Length; i++)
                {
                    for (int j = 0; j < Lines[i].Length; j++)
                    {
                        if (Lines[i][j] == '"')
                        {
                            Quote = !Quote;
                        }

                        if (!Quote)
                        {
                            if (Lines[i][j] == '#' || j < Lines[i].Length - 1 && Lines[i].Substring(j, 2) == "//")
                            {
                                Lines[i] = Lines[i].Substring(0, j);
                                break;
                            }
                        }
                    }
                    //Convert runs of whitespace to single
                    var list = Lines[i].Split(' ').Where(s => !string.IsNullOrWhiteSpace(s));
                    Lines[i] = string.Join(" ", list);
                }
                StringBuilder Builder = new StringBuilder();
                for (int i = 0; i < Lines.Length; i++)
                {
                    Builder.Append(Lines[i]);
                    Builder.Append(" ");
                }
                string Content = Builder.ToString();
                Content = Content.Substring(17).Trim();
                return(LoadTextualX(Content));
            }

            byte[] newData;
            if (Data[8] == 98 & Data[9] == 105 & Data[10] == 110 & Data[11] == 32)
            {
                //Uncompressed binary, so skip the header
                newData = new byte[Data.Length - 16];
                Array.Copy(Data, 16, newData, 0, Data.Length - 16);
                return(LoadBinaryX(newData, FloatingPointSize));
            }

            if (Data[8] == 116 & Data[9] == 122 & Data[10] == 105 & Data[11] == 112)
            {
                // compressed textual flavor
                newData = MSZip.Decompress(Data);
                string Text = Encoding.GetString(newData);
                return(LoadTextualX(Text));
            }

            if (Data[8] == 98 & Data[9] == 122 & Data[10] == 105 & Data[11] == 112)
            {
                //Compressed binary
                //16 bytes of header, then 8 bytes of padding, followed by the actual compressed data
                byte[] Uncompressed = MSZip.Decompress(Data);
                return(LoadBinaryX(Uncompressed, FloatingPointSize));
            }

            // unsupported flavor
            Interface.AddMessage(MessageType.Error, false, "Unsupported X object file encountered in " + FileName);
            return(null);
        }
예제 #15
0
 private Topology.Converters.WellKnownText.TokenType NextTokenAny()
 {
     Topology.Converters.WellKnownText.TokenType eof = Topology.Converters.WellKnownText.TokenType.Eof;
     char[] chArray = new char[1];
     this._currentToken = "";
     this._currentTokenType = Topology.Converters.WellKnownText.TokenType.Eof;
     int num = this._reader.Read(chArray, 0, 1);
     bool flag = false;
     bool flag2 = false;
     byte[] bytes = null;
     ASCIIEncoding encoding = new ASCIIEncoding();
     char[] chars = null;
     while (num != 0)
     {
         bytes = new byte[] { (byte) this._reader.Peek() };
         chars = encoding.GetChars(bytes);
         char character = chArray[0];
         char ch2 = chars[0];
         this._currentTokenType = this.GetType(character);
         eof = this.GetType(ch2);
         if (flag2 && (character == '_'))
         {
             this._currentTokenType = Topology.Converters.WellKnownText.TokenType.Word;
         }
         if (flag2 && (this._currentTokenType == Topology.Converters.WellKnownText.TokenType.Number))
         {
             this._currentTokenType = Topology.Converters.WellKnownText.TokenType.Word;
         }
         if ((this._currentTokenType == Topology.Converters.WellKnownText.TokenType.Word) && (ch2 == '_'))
         {
             eof = Topology.Converters.WellKnownText.TokenType.Word;
             flag2 = true;
         }
         if ((this._currentTokenType == Topology.Converters.WellKnownText.TokenType.Word) && (eof == Topology.Converters.WellKnownText.TokenType.Number))
         {
             eof = Topology.Converters.WellKnownText.TokenType.Word;
             flag2 = true;
         }
         if (((character == '-') && (eof == Topology.Converters.WellKnownText.TokenType.Number)) && !flag)
         {
             this._currentTokenType = Topology.Converters.WellKnownText.TokenType.Number;
             eof = Topology.Converters.WellKnownText.TokenType.Number;
         }
         if ((flag && (eof == Topology.Converters.WellKnownText.TokenType.Number)) && (character == '.'))
         {
             this._currentTokenType = Topology.Converters.WellKnownText.TokenType.Number;
         }
         if (((this._currentTokenType == Topology.Converters.WellKnownText.TokenType.Number) && (ch2 == '.')) && !flag)
         {
             eof = Topology.Converters.WellKnownText.TokenType.Number;
             flag = true;
         }
         this._colNumber++;
         if (this._currentTokenType == Topology.Converters.WellKnownText.TokenType.Eol)
         {
             this._lineNumber++;
             this._colNumber = 1;
         }
         this._currentToken = this._currentToken + character;
         if (this._currentTokenType != eof)
         {
             num = 0;
         }
         else
         {
             if ((this._currentTokenType == Topology.Converters.WellKnownText.TokenType.Symbol) && (character != '-'))
             {
                 num = 0;
                 continue;
             }
             num = this._reader.Read(chArray, 0, 1);
         }
     }
     return this._currentTokenType;
 }
예제 #16
0
 public void TestSystemIdForMbr() {
     Adder adder = m_testService.CreateNewWithSystemID();
     string marshalUrl = RemotingServices.GetObjectUri(adder);
     Ior adderIor = new Ior(marshalUrl);
     IInternetIiopProfile prof = adderIor.FindInternetIiopProfile();
     byte[] objectKey = prof.ObjectKey;
     ASCIIEncoding enc = new ASCIIEncoding();
     string marshalUri = new String(enc.GetChars(objectKey));
     if (marshalUri.StartsWith("/")) {
         marshalUri = marshalUri.Substring(1);
     }
     Assert.IsTrue(marshalUri.IndexOf("/") > 0, "no appdomain-guid");
     string guid_string = marshalUri.Substring(0, marshalUri.IndexOf("/"));
     guid_string = guid_string.Replace("_", "-");
     try {
         Guid guid = new Guid(guid_string);
     } catch (Exception ex) {
         Assert.Fail("guid not in uri: " + ex);
     }
     
     // check if callable
     int arg1 = 1;
     int arg2 = 2;
     Assert.AreEqual(arg1 + arg2, adder.Add(arg1, arg2), "wrong adder result");
 }
예제 #17
0
        public void GetChars_Performance()
        {
            var input = new byte[2000];
            new Random().NextBytes(input);
            const int loopCount = 100000;

            var corefxAscii = new System.Text.ASCIIEncoding();
            var sshAscii = _ascii;

            var stopWatch = new Stopwatch();

            GC.Collect();
            GC.WaitForFullGCComplete();

            stopWatch.Start();

            for (var i = 0; i < loopCount; i++)
            {
                var actual = corefxAscii.GetChars(input);
            }

            stopWatch.Stop();

            Console.WriteLine(stopWatch.ElapsedMilliseconds);

            stopWatch.Reset();

            GC.Collect();
            GC.WaitForFullGCComplete();

            stopWatch.Start();

            for (var i = 0; i < loopCount; i++)
            {
                var actual = sshAscii.GetChars(input);
            }

            stopWatch.Stop();

            Console.WriteLine(stopWatch.ElapsedMilliseconds);
        }
        /// <summary>
        /// Wait for a packet.  Timeout if necessary.
        /// </summary>
        public void WaitForPacket()
        {
            var line = new StringBuilder();
            var buffer = new byte[1024];
            var charBuffer = new char[1024];
            var actualSize = 0;

            // if there was an error, nothing to wait for.
            if( this._indicatorState == IndicatorState.Error )
            {
                return;
            }

            // attempt to get a packet
            try
            {
                actualSize = _sock.Receive(buffer);
            }
            catch(SocketException ex)
            {
                PerformError("Socket Error: " + ex.Message);
                return;
            }

            // If we got a packet, then process it.
            if( actualSize>0 ) {
                // packets are in ASCII
                ASCIIEncoding ascii = new ASCIIEncoding();
                ascii.GetChars(buffer,0,actualSize,charBuffer,0);

                // Break up the packets, they are ASCII lines.
                for(int i=0;i<actualSize;i++)
                {
                    char ch = (char)charBuffer[i];

                    if( ch!='\n' && ch!='\r' )
                    {
                        line.Append(ch);
                    }
                    else
                    {
                        if( line.Length>0 )
                        {
                            GotPacket(line.ToString());
                                line.Length = 0;
                        }
                    }
                }
            }
        }
예제 #19
0
        static public Property Parse(XmlNode firstProperty, string context)
        {
            Property rootProperty = new Property();

            rootProperty.Context = context;

            rootProperty.Name     = firstProperty.Attributes["name"].Value;
            rootProperty.FullName = firstProperty.Attributes["fullname"].Value;

            string propType = firstProperty.Attributes["type"].Value;

            if (propType != "array" && propType != "object")
            {
                if (firstProperty.Attributes["encoding"] != null)
                {
                    if (firstProperty.Attributes["encoding"].Value == "base64")
                    {
                        byte[] todecode_byte        = Convert.FromBase64String(firstProperty.InnerText);
                        System.Text.Decoder decoder = new System.Text.ASCIIEncoding().GetDecoder();

                        int    charCount    = decoder.GetCharCount(todecode_byte, 0, todecode_byte.Length);
                        char[] decoded_char = new char[charCount];
                        decoder.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
                        string result = new String(decoded_char);

                        rootProperty.Value = result;
                    }
                }
                else
                {
                    rootProperty.Value = firstProperty.InnerText;
                }

                rootProperty.isComplete = true;
                rootProperty.Type       = PropertyType.Scalar;

                return(rootProperty);
            }
            else
            {
                rootProperty.isComplete = false;
                rootProperty.Type       = (propType == "array") ? PropertyType.Array : PropertyType.Object;

                if (propType == "array")
                {
                    rootProperty.Value = "Array (" + (firstProperty.Attributes["numchildren"] != null ? firstProperty.Attributes["numchildren"].Value : "") + ")";
                }
                else
                {
                    rootProperty.Value = "Instance of " + firstProperty.Attributes["classname"].Value;
                }

                if (firstProperty.Attributes["children"].Value == "0")
                {
                    rootProperty.isComplete = true;
                }
                else
                {
                    int numChildren = firstProperty.Attributes["numchildren"] != null?Convert.ToInt32(firstProperty.Attributes["numchildren"].Value) : 0;

                    rootProperty.isComplete = numChildren > 0 && numChildren == firstProperty.ChildNodes.Count;

                    foreach (XmlNode node in firstProperty.ChildNodes)
                    {
                        if (node.Attributes["name"].Value == "CLASSNAME")
                        {
                            continue;                                               // this is to handle http://bugs.xdebug.org/bug_view_page.php?bug_id=00000518
                        }
                        rootProperty.ChildProperties.Add(Property.Parse(node, context));
                    }
                }
            }


            return(rootProperty);
        }
예제 #20
0
 /// <summary>
 /// Decrypt the encryption stored in this byte array.
 /// </summary>
 /// <param name="encryptedBytes">The byte array to decrypt.</param>
 /// <param name="password">The password to use when decrypting.</param>
 /// <returns></returns>
 /// <remarks></remarks>
 public static String DecryptFromByteArray(this Byte[] encryptedBytes, String password)
 {
     var decryptedBytes = CryptBytes(password, encryptedBytes, false);
     var asciiEncoder = new ASCIIEncoding();
     return new String(asciiEncoder.GetChars(decryptedBytes));
 }
예제 #21
0
파일: Program.cs 프로젝트: Deson621/demo
        static void Main(string[] args)
        {
            #region 测试注释

            //var barr= new byte[] { 0x00, 0x8D };
            //char c = '1';
            //string str = "1";

            ////List<byte> list = new List<byte>();
            ////foreach (var item in "李".ToCharArray())
            ////{
            ////    var b = System.Convert.ToString(item, 16);
            ////    list.Add(Tool.GetEncoding().GetBytes(b));
            ////}
            //var buff= Tool.GetEncoding().GetBytes("李俊");
            //var bitstr = BitConverter.ToString(buff).Split('-').Select(s => s).ToArray();
            //var get= Tool.GetEncoding().GetBytes("133");

            //Console.Read();
            byte[] list = new byte[]{
            0xd6, 0xd0, 0xb9,
            0xfa,0xb9, 0xa4,0xc9,0xcc, 0xd2,0xf8,0xd0,
            0xd0,0xc4,0xb5,0xb5,0xa4,0xbf,0xa8,0x20
            ,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20
            ,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20
            ,0x20,0x20,0x20,0x20,0x20
            };
            var e = Encoding.GetEncoding("GBK").GetString(list);
            Console.WriteLine(e);
            string name = "中国工商银行牡丹卡";
            var en = Encoding.GetEncoding("GBK").GetBytes(name);
            //把ASCII码转化为对应的字符
            ASCIIEncoding AE2 = new ASCIIEncoding();
            byte[] ByteArray2 = { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100 };
            char[] CharArray = AE2.GetChars(ByteArray2);
            for (int x = 0; x <= CharArray.Length - 1; x++)
            {
                Console.Write(CharArray[x]);
            }

            var u = Encoding.ASCII.GetBytes(name);

            var str = Tool.GetEncoding().GetChars(list);

            //RequestData data = new RequestData();
            //var v = DataEntityAttributeHelper.GetDataLength<ResponseData>(p => p.TPDU);
            #endregion

            using (AsyncSocketService asyncSocketService = new AsyncSocketService(int.Parse(ConfigurationManager.AppSettings["port"])))
            {

            }
            //TcpListenerSocketService tcpListen = new TcpListenerSocketService();
            #region MyRegion
            //TcpListener tcpListenerServer = new TcpListener(IPAddress.Any, 12345);
            //tcpListenerServer.Start();
            //Console.WriteLine("等待连接");
            //TcpClient tcpClient = tcpListenerServer.AcceptTcpClient();

            //while (true)
            //{
            //    Console.WriteLine("连接成功");
            //    try
            //    {
            //        byte[] data = new byte[1024];
            //        int bytes = tcpClient.Client.Receive(data, data.Length, 0);
            //        string recStr = Encoding.ASCII.GetString(data, 0, bytes);
            //        Console.WriteLine(recStr);

            //        string sendStr = "";
            //        byte[] sendBytes = Encoding.ASCII.GetBytes(sendStr);
            //        tcpClient.Client.Send(sendBytes);
            //    }
            //    catch (Exception ex)
            //    {
            //        Console.WriteLine(ex.Message);
            //        tcpClient.Close();
            //        Console.WriteLine("等待连接");
            //        tcpClient = tcpListenerServer.AcceptTcpClient();
            //    }
            //}
            #endregion
        }
예제 #22
0
 private void ReadHeader(BinaryReader r)
 {
     byte[] header = r.ReadBytes(10);
     ASCIIEncoding e = new ASCIIEncoding();
     byte[] desiredHeader = e.GetBytes("MS3D000000");
     Int32 version = r.ReadInt32();
     if (!thisShouldExistAlready(header, desiredHeader))
     {
         Console.WriteLine(e.GetChars(header));
         Console.WriteLine(e.GetChars(desiredHeader));
         Error("Unknown data type!");
     }
     if (version != 4)
     {
         Error("Bad MS3D version!  Use version 4.");
     }
 }
예제 #23
0
 public void TestUserIdForMbr() {
     string id = "myAdderId";
     Adder adder = m_testService.CreateNewWithUserID(id);
     string marshalUrl = RemotingServices.GetObjectUri(adder);
     Ior adderIor = new Ior(marshalUrl);
     IInternetIiopProfile prof = adderIor.FindInternetIiopProfile();
     byte[] objectKey = prof.ObjectKey;
     ASCIIEncoding enc = new ASCIIEncoding();
     string marshalUri = new String(enc.GetChars(objectKey));
     Assert.AreEqual(id, marshalUri, "wrong user id");
     
     // check if callable
     int arg1 = 1;
     int arg2 = 2;
     Assert.AreEqual(arg1 + arg2, adder.Add(arg1, arg2), "wrong adder result");
 }
예제 #24
0
        private static bool processGcPage(string url, byte[] dataDownloaded)
        {
            bool ret = false;

            int lineno = 0;
            string line;
            int state = 0;
            string lineToSearch = "<span id=\"CacheName\">";
            int pos;
            string cacheName = "";

            ASCIIEncoding enc = new ASCIIEncoding();
            string pageText = new String(enc.GetChars(dataDownloaded));

            CreateInfo createInfo = new CreateInfo();	// we will recycle it in place, filling every time.

            StringReader stream = new StringReader(pageText);

            try
            {
                while((line = stream.ReadLine()) != null && state < 99)
                {
                    lineno++;
                    switch(state)
                    {
                        case 0:
                            if((pos = line.IndexOf(lineToSearch)) != -1)
                            {
                                pos += lineToSearch.Length;
                                int pos1 = line.IndexOf("</span>", pos);
                                if(pos1 > pos)
                                {
                                    cacheName = line.Substring(pos, pos1-pos).Trim();
                                    LibSys.StatusBar.Trace("OK: cacheName='" + cacheName + "'");

                                    state = 1;
                                    lineToSearch = "<span id=\"LatLon\"";
                                }
                            }
                            break;
                        case 1:
                            if((pos = line.IndexOf(lineToSearch)) != -1)
                            {
                                pos += lineToSearch.Length;
                                int pos1 = line.IndexOf("</span>", pos);
                                if(pos1 > pos)
                                {
                                    string sCacheCoords = line.Substring(pos, pos1-pos).Trim();
                                    LibSys.StatusBar.Trace("OK: cacheCoords='" + sCacheCoords + "'");
                                    GeoCoord loc = getCleanLocation(sCacheCoords);
                                    //LibSys.StatusBar.Trace("OK: loc='" + loc + "'");

                                    createInfo.init("wpt");
                                    createInfo.lat = loc.Lat;
                                    createInfo.lng = loc.Lng;
                                    createInfo.typeExtra = "geocache";
                                    createInfo.source = url;
                                    createInfo.name = cacheName;
                                    createInfo.url = url;

                                    WaypointsCache.insertWaypoint(createInfo);

                                    WaypointsCache.isDirty = true;

                                    ret = true;	// report successfully parsed page
                                    state = 99;
                                    lineToSearch = "";
                                }
                            }
                            break;
                    }
                }
            }
            catch {}

            return ret;
        }
예제 #25
0
 public void TestIdsIncludingNonAscii() {
     string id = "myAdderId" + '\u0765' + "1" + @"\uA";
     string expectedMarshalledId = @"myAdderId\u07651\\uA";
     Adder adder = m_testService.CreateNewWithUserID(id);
     string marshalUrl = RemotingServices.GetObjectUri(adder);
     Ior adderIor = new Ior(marshalUrl);
     IInternetIiopProfile prof = adderIor.FindInternetIiopProfile();
     byte[] objectKey = prof.ObjectKey;
     ASCIIEncoding enc = new ASCIIEncoding();
     string marshalUri = new String(enc.GetChars(objectKey));
     Assert.AreEqual(expectedMarshalledId, marshalUri, "wrong user id");
     
     // check if callable
     int arg1 = 1;
     int arg2 = 2;
     Assert.AreEqual(arg1 + arg2, adder.Add(arg1, arg2), "wrong adder result");
 }
예제 #26
0
		//随即产生一个字母
		char GenerateChar()
		{
			Byte[] bytes = new Byte[1];
			Char[] chars = new Char[1];
			ASCIIEncoding ascii = new ASCIIEncoding();
			//产生一个从字母a到字母z中间的任何一个字符
			bytes[0] = (Byte)(randomNumberGenerator.Next(97,123));

			ascii.GetChars(bytes, 0, 1, chars, 0);

			return chars[0];
			
		}
예제 #27
0
        static public Property Parse(XmlNode firstProperty)
        {
            Property rootProperty = new Property();

            rootProperty.Name     = firstProperty.Attributes["name"].Value;
            rootProperty.FullName = firstProperty.Attributes["fullname"].Value;

            string propType = firstProperty.Attributes["type"].Value;

            if (propType != "array" && propType != "object")
            {
                if (firstProperty.Attributes["encoding"] != null)
                {
                    if (firstProperty.Attributes["encoding"].Value == "base64")
                    {
                        byte[] todecode_byte        = Convert.FromBase64String(firstProperty.InnerText);
                        System.Text.Decoder decoder = new System.Text.ASCIIEncoding().GetDecoder();

                        int    charCount    = decoder.GetCharCount(todecode_byte, 0, todecode_byte.Length);
                        char[] decoded_char = new char[charCount];
                        decoder.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
                        string result = new String(decoded_char);

                        rootProperty.Value = result;
                    }
                }
                else
                {
                    rootProperty.Value = firstProperty.InnerText;
                }

                rootProperty.isComplete = true;
                rootProperty.Type       = PropertyType.Scalar;

                return(rootProperty);
            }
            else
            {
                rootProperty.isComplete = false;
                rootProperty.Type       = (propType == "array") ? PropertyType.Array : PropertyType.Object;

                if (propType == "array")
                {
                    rootProperty.Value = "Array (" + firstProperty.Attributes["numchildren"].Value + ")";
                }
                else
                {
                    rootProperty.Value = "Instance of " + firstProperty.Attributes["classname"].Value;
                }

                if (firstProperty.Attributes["children"].Value == "0")
                {
                    rootProperty.isComplete = true;
                }
                else
                {
                    int numChildren = Convert.ToInt32(firstProperty.Attributes["numchildren"].Value);
                    rootProperty.isComplete = numChildren == firstProperty.ChildNodes.Count;

                    foreach (XmlNode node in firstProperty.ChildNodes)
                    {
                        rootProperty.ChildProperties.Add(Property.Parse(node));
                    }
                }
            }


            return(rootProperty);
        }
예제 #28
0
        private TokenType NextTokenAny()
        {
            TokenType nextTokenType = TokenType.Eof;
            char[] chars = new char[1];
            _currentToken="";
            _currentTokenType = TokenType.Eof;
            int finished = _reader.Read(chars,0,1);

            bool isNumber=false;
            bool isWord=false;
            byte[] ba=null;
            #if SILVERLIGHT
            Encoding AE = System.Text.Encoding.Unicode;
            #else
            ASCIIEncoding AE = new ASCIIEncoding();
            #endif
            char[] ascii=null;
            Char currentCharacter;
            Char nextCharacter;
            while (finished != 0 )
            {
                // convert int to char
                ba = new Byte[]{(byte)_reader.Peek()};

                 ascii = AE.GetChars(ba);

                currentCharacter = chars[0];
                nextCharacter = ascii[0];
                _currentTokenType = GetType(currentCharacter);
                nextTokenType = GetType(nextCharacter);

                // handling of words with _
                if (isWord && currentCharacter=='_')
                {
                    _currentTokenType= TokenType.Word;
                }
                // handing of words ending in numbers
                if (isWord && _currentTokenType==TokenType.Number)
                {
                    _currentTokenType= TokenType.Word;
                }

                if (_currentTokenType==TokenType.Word && nextCharacter=='_')
                {
                    //enable words with _ inbetween
                    nextTokenType =  TokenType.Word;
                    isWord=true;
                }
                if (_currentTokenType==TokenType.Word && nextTokenType==TokenType.Number)
                {
                    //enable words ending with numbers
                    nextTokenType =  TokenType.Word;
                    isWord=true;
                }

                // handle negative numbers
                if (currentCharacter=='-' && nextTokenType==TokenType.Number && isNumber ==false)
                {
                    _currentTokenType= TokenType.Number;
                    nextTokenType =  TokenType.Number;
                    //isNumber = true;
                }

                // this handles numbers with a decimal point
                if (isNumber && nextTokenType == TokenType.Number && currentCharacter=='.' )
                {
                    _currentTokenType =  TokenType.Number;
                }
                if (_currentTokenType == TokenType.Number && nextCharacter=='.' && isNumber ==false)
                {
                    nextTokenType =  TokenType.Number;
                    isNumber = true;
                }

                _colNumber++;
                if (_currentTokenType==TokenType.Eol)
                {
                    _lineNumber++;
                    _colNumber=1;
                }

                _currentToken = _currentToken + currentCharacter;
                //if (_currentTokenType==TokenType.Word && nextCharacter=='_')
                //{
                    // enable words with _ inbetween
                //	finished = _reader.Read(chars,0,1);
                //}
                if (_currentTokenType!=nextTokenType)
                {
                    finished = 0;
                }
                else if (_currentTokenType==TokenType.Symbol && currentCharacter!='-')
                {
                    finished = 0;
                }
                else
                {
                    finished = _reader.Read(chars,0,1);
                }
            }
            return _currentTokenType;
        }
예제 #29
0
        public void NegTest5()
        {
            ASCIIEncoding ascii = new ASCIIEncoding();
            byte[] bytes = null;

            Assert.Throws<ArgumentNullException>(() =>
            {
                ascii.GetChars(bytes, 0, 0, new char[0], 0);
            });
        }
예제 #30
0
        public static Property Parse(XmlNode firstProperty, string context)
        {
            Property rootProperty = new Property();
            rootProperty.Context = context;

            rootProperty.Name = firstProperty.Attributes["name"].Value;
            rootProperty.FullName = firstProperty.Attributes["fullname"].Value;

            string propType = firstProperty.Attributes["type"].Value;

            if (propType != "array" && propType != "object")
            {
                if (firstProperty.Attributes["encoding"] != null)
                {
                    if (firstProperty.Attributes["encoding"].Value == "base64")
                    {
                        byte[] todecode_byte = Convert.FromBase64String(firstProperty.InnerText);
                        System.Text.Decoder decoder = new System.Text.ASCIIEncoding().GetDecoder();

                        int charCount = decoder.GetCharCount(todecode_byte, 0, todecode_byte.Length);
                        char[] decoded_char = new char[charCount];
                        decoder.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
                        string result = new String(decoded_char);

                        rootProperty.Value = result;
                    }
                }
                else
                {
                    rootProperty.Value = firstProperty.InnerText;
                }

                rootProperty.isComplete = true;
                rootProperty.Type = PropertyType.Scalar;

                return rootProperty;
            }
            else
            {
                rootProperty.isComplete = false;
                rootProperty.Type = (propType == "array") ? PropertyType.Array : PropertyType.Object;

                if (propType == "array")
                {
                    rootProperty.Value = "Array (" + (firstProperty.Attributes["numchildren"] != null ? firstProperty.Attributes["numchildren"].Value : "") + ")";
                } else {
                    rootProperty.Value = "Instance of " + firstProperty.Attributes["classname"].Value;
                 }

                if (firstProperty.Attributes["children"].Value == "0")
                {
                    rootProperty.isComplete = true;
                }
                else
                {
                    int numChildren = firstProperty.Attributes["numchildren"] != null ? Convert.ToInt32(firstProperty.Attributes["numchildren"].Value) : 0;
                    rootProperty.isComplete = numChildren > 0 && numChildren == firstProperty.ChildNodes.Count;

                    foreach (XmlNode node in firstProperty.ChildNodes)
                    {
                        if (node.Attributes["name"].Value == "CLASSNAME") continue; // this is to handle http://bugs.xdebug.org/bug_view_page.php?bug_id=00000518
                        rootProperty.ChildProperties.Add(Property.Parse(node, context));
                    }
                }
            }

            return rootProperty;
        }
예제 #31
0
        protected virtual string ReadLine()
        {
            byte[] bs = null;
            LineParser linePaser = new LineParser();

            ASCIIEncoding aSCIIEncoding = new ASCIIEncoding();

            while ((bs = ReadByte()) != null)
            {
                linePaser.Write(aSCIIEncoding.GetChars(bs));

                string strNextLine = linePaser.ReadLine();
                if (strNextLine != null)
                {
                    return strNextLine;
                }
            }

            throw new Pop3ServerIncorectAnswerException();
        }
예제 #32
0
        public void NegTest6()
        {
            ASCIIEncoding ascii = new ASCIIEncoding();
            byte[] bytes = new byte[]
            {
             65,  83,  67,  73,  73,  32,  69,
            110,  99, 111, 100, 105, 110, 103,
             32,  69, 120,  97, 109, 112, 108
            };

            Assert.Throws<ArgumentNullException>(() =>
            {
                ascii.GetChars(bytes, 0, 0, null, 0);
            });
        }
예제 #33
0
 private void DoNegAOORTest(ASCIIEncoding ascii, byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
 {
     Assert.Throws<ArgumentOutOfRangeException>(() =>
     {
         ascii.GetChars(bytes, byteIndex, byteCount, chars, charIndex);
     });
 }
예제 #34
0
 private void DoPosTest(ASCIIEncoding ascii, byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
 {
     int actualValue = ascii.GetChars(bytes, byteIndex, byteCount, chars, charIndex);
     Assert.True(VerifyGetCharsResult(ascii, bytes, byteIndex, byteCount, chars, charIndex, actualValue));
 }
예제 #35
0
파일: Client.cs 프로젝트: zobo/xdebugclient
        /// <summary>
        /// Turn Base64 encoded text into ASCII.
        /// </summary>        
        private string base64ToASCII(string text)
        {
            byte[] todecode_byte = Convert.FromBase64String(text);
            System.Text.Decoder decoder = new System.Text.ASCIIEncoding().GetDecoder();

            int charCount = decoder.GetCharCount(todecode_byte, 0, todecode_byte.Length);
            char[] decoded_char = new char[charCount];
            decoder.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);

            return new String(decoded_char);
        }
예제 #36
0
파일: Parser.cs 프로젝트: sladen/openbve2
 // load from file
 /// <summary>Loads a .X object from a file and returns the success of the operation.</summary>
 /// <param name="fileName">The platform-specific absolute file name of the object.</param>
 /// <param name="fallback">The fallback encoding.</param>
 /// <param name="obj">Receives a compatible mesh from the object data, or null if the file could not be processed.</param>
 /// <returns>The success of the operation.</returns>
 internal static OpenBveApi.General.Result LoadFromFile(string fileName, System.Text.Encoding fallback, out OpenBveApi.Geometry.GenericObject obj)
 {
     /*
      * initialize
      */
     OpenBveApi.Geometry.GenericObject mesh = null;
     obj = null;
     /*
      * prepare
      */
     byte[] data = System.IO.File.ReadAllBytes(fileName);
     if (data.Length < 16 || data[0] != 120 | data[1] != 111 | data[2] != 102 | data[3] != 32) {
         /*
          * not an x object
          */
         IO.ReportError(fileName, "Invalid X object file encountered");
         return OpenBveApi.General.Result.InvalidData;
     }
     if (data[4] != 48 | data[5] != 51 | data[6] != 48 | data[7] != 50 & data[7] != 51) {
         /*
          * unrecognized version
          */
         System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding();
         string s = new string(ascii.GetChars(data, 4, 4));
         IO.ReportError(fileName, "Unsupported X object file version " + s + " encountered");
     }
     /*
      * floating-point format
      */
     int floatingPointSize;
     if (data[12] == 48 & data[13] == 48 & data[14] == 51 & data[15] == 50) {
         floatingPointSize = 32;
     } else if (data[12] == 48 & data[13] == 48 & data[14] == 54 & data[15] == 52) {
         floatingPointSize = 64;
     } else {
         IO.ReportError(fileName, "Unsupported floating point format encountered in X object");
         return OpenBveApi.General.Result.InvalidData;
     }
     /*
      * supported floating point format
      */
     if (data[8] == 116 & data[9] == 120 & data[10] == 116 & data[11] == 32) {
         /*
          * textual flavor
          */
         mesh = LoadTextualX(fileName, System.IO.File.ReadAllText(fileName), fallback);
     } else if (data[8] == 98 & data[9] == 105 & data[10] == 110 & data[11] == 32) {
         /*
          * binary flavor
          */
         mesh = LoadBinaryX(fileName, data, 16, fallback, floatingPointSize);
     } else if (data[8] == 116 & data[9] == 122 & data[10] == 105 & data[11] == 112) {
         /*
          * compressed textual flavor
          */
         #if !DEBUG
         try {
             #endif
             byte[] uncompressed = Decompress(data);
             string text = fallback.GetString(uncompressed);
             mesh = LoadTextualX(fileName, text, fallback);
             #if !DEBUG
         } catch (Exception ex) {
             IO.ReportError(fileName, true, "An unexpected error occured (" + ex.Message + ")  while attempting to decompress data");
             return OpenBveApi.General.Result.InvalidData;
         }
         #endif
     } else if (data[8] == 98 & data[9] == 122 & data[10] == 105 & data[11] == 112) {
         /*
          * compressed binary flavor
          */
         #if !DEBUG
         try {
             #endif
             byte[] uncompressed = Decompress(data);
             mesh = LoadBinaryX(fileName, uncompressed, 0, fallback, floatingPointSize);
             #if !DEBUG
         } catch (Exception ex) {
             IO.ReportError(fileName, true, "An unexpected error occured (" + ex.Message + ")  while attempting to decompress data");
             return OpenBveApi.General.Result.InvalidData;
         }
         #endif
     } else {
         /*
          * unsupported flavor
          */
         IO.ReportError(fileName, "Unsupported X object file encountered");
         return OpenBveApi.General.Result.InvalidData;
     }
     /*
      * finish
      */
     if (mesh != null) {
         obj = (OpenBveApi.Geometry.GenericObject)mesh;
         return OpenBveApi.General.Result.Successful;
     } else {
         return OpenBveApi.General.Result.InvalidData;
     }
 }