GetBytes() private method

private GetBytes ( char chars, int charCount, byte bytes, int byteCount, bool flush ) : int
chars char
charCount int
bytes byte
byteCount int
flush bool
return int
 internal static string GetMd5Sum(string str)
 {
     System.Text.Encoder encoder = Encoding.Unicode.GetEncoder();
     byte[] numArray             = new byte[str.Length * 2];
     encoder.GetBytes(str.ToCharArray(), 0, str.Length, numArray, 0, true);
     return(GetMd5Sum(numArray));
 }
示例#2
0
        private unsafe void CreateFirstSubstData(string s, IIS7WorkerRequest iis7WorkerRequest, System.Text.Encoder encoder)
        {
            IntPtr ptr;
            int    num    = 0;
            int    length = s.Length;

            if (length > 0)
            {
                fixed(char *str = ((char *)s))
                {
                    char *chars = str;
                    int   size  = encoder.GetByteCount(chars, length, true);

                    ptr = iis7WorkerRequest.AllocateRequestMemory(size);
                    if (ptr != IntPtr.Zero)
                    {
                        num = encoder.GetBytes(chars, length, (byte *)ptr, size, true);
                    }
                }
            }
            else
            {
                ptr = iis7WorkerRequest.AllocateRequestMemory(1);
            }
            if (ptr == IntPtr.Zero)
            {
                throw new OutOfMemoryException();
            }
            this._firstSubstData     = ptr;
            this._firstSubstDataSize = num;
        }
示例#3
0
 public static int Hash(string data, Encoder enc)
 {
     var arr = data.ToCharArray();
     int count = enc.GetByteCount(arr, 0, arr.Length, false);
     var bytes = new byte[count];
     enc.GetBytes(arr, 0, arr.Length, bytes, 0, false);
     return Hash(bytes);
 }
示例#4
0
		/// <summary>
		/// Loads the [HKEY_LOCAL_MACHINE\SOFTWARE\HolodeckEE\PaneSettings] registry value from the specified file
		/// </summary>
		/// <param name="inputFilePath">the path of the file to read from</param>
		public static void LoadPaneSettings (string inputFilePath)
		{
			System.IO.StreamReader inputFile = new System.IO.StreamReader (inputFilePath);
			string fileContent = inputFile.ReadToEnd ();
			char[] newRegPaneSettings = fileContent.ToCharArray ();
			System.Text.Encoder encoder = System.Text.Encoding.Unicode.GetEncoder ();
			byte[] encodedPaneSettings = new byte[newRegPaneSettings.Length * 2];
			encoder.GetBytes (newRegPaneSettings, 0, newRegPaneSettings.Length, encodedPaneSettings, 0, true);
			Microsoft.Win32.Registry.LocalMachine.OpenSubKey ("SOFTWARE\\HolodeckEE", true).SetValue ("PaneSettings", encodedPaneSettings);
		}
示例#5
0
        public static byte[] EncodeString(string vValue)
        {
            string str = vValue;

            System.Text.Encoder encoder = m_encoding.GetEncoder();
            char[] chars = str.ToCharArray();
            byte[] bytes = new byte[encoder.GetByteCount(chars, 0, chars.Length, false)];
            encoder.GetBytes(chars, 0, chars.Length, bytes, 0, true);
            return(Mogo.RPC.Utils.FillLengthHead(bytes));
        }
        private static unsafe int UnsafeAppendEncodedChars(char[] src, int srcOffset, int srcSize, IntPtr dest, int destOffset, int destSize, System.Text.Encoder encoder, bool flushEncoder)
        {
            int   num   = 0;
            byte *bytes = (byte *)(((void *)dest) + destOffset);

            fixed(char *chRef = src)
            {
                num = encoder.GetBytes(chRef + srcOffset, srcSize, bytes, destSize, flushEncoder);
            }

            return(num);
        }
示例#7
0
        static string GetMd5Sum(string productIdentifier)
        {
            System.Text.Encoder enc = System.Text.Encoding.Unicode.GetEncoder();
            byte[] unicodeText      = new byte[productIdentifier.Length * 2];
            enc.GetBytes(productIdentifier.ToCharArray(), 0, productIdentifier.Length, unicodeText, 0, true);
            MD5 md5 = new MD5CryptoServiceProvider();

            byte[] result = md5.ComputeHash(unicodeText);

            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < result.Length; i++)
            {
                sb.Append(result[i].ToString("X2"));
            }
            return(sb.ToString());
        }
示例#8
0
        /// <summary>
        /// Add a standard EXIF field to the image
        /// </summary>
        /// <param name="image"></param>
        /// <param name="field"></param>
        /// <param name="fieldValue"></param>
        private static void WriteEXIFField(Image image, ExifField field, string fieldValue)
        {
            Encoding asciiEncoding = new ASCIIEncoding();

            System.Text.Encoder encoder = asciiEncoding.GetEncoder();
            char[] tagTextChars         = fieldValue.ToCharArray();
            int    byteCount            = encoder.GetByteCount(tagTextChars, 0, tagTextChars.Length, true);

            byte[] tagTextBytes = new byte[byteCount];
            encoder.GetBytes(tagTextChars, 0, tagTextChars.Length, tagTextBytes, 0, true);

            if (image.PropertyItems != null && image.PropertyItems.Length > 0)
            {
                PropertyItem propertyItem = image.PropertyItems[0];
                propertyItem.Id    = (int)field;
                propertyItem.Type  = 2; // ASCII
                propertyItem.Len   = tagTextBytes.Length;
                propertyItem.Value = tagTextBytes;
                image.SetPropertyItem(propertyItem);
            }
        }
        // GET api/<controller>
        public HttpResponseMessage Get(string filename, string ext)
        {
            if (filename == null)
            {
                return(new HttpResponseMessage(HttpStatusCode.BadRequest));
            }

            string filePath = HostingEnvironment.MapPath("~/Videos/") + filename + "." + ext;

            if (Request.Headers.Range != null)
            {
                try
                {
                    System.Text.Encoder stringEncoder = Encoding.UTF8.GetEncoder();
                    byte[] stringBytes = new byte[stringEncoder.GetByteCount(filePath.ToCharArray(), 0, filePath.Length, true)];
                    stringEncoder.GetBytes(filePath.ToCharArray(), 0, filePath.Length, stringBytes, 0, true);
                    MD5CryptoServiceProvider MD5Enc = new MD5CryptoServiceProvider();
                    string hash = BitConverter.ToString(MD5Enc.ComputeHash(stringBytes)).Replace("-", string.Empty);

                    HttpResponseMessage partialResponse = Request.CreateResponse(HttpStatusCode.PartialContent);
                    partialResponse.Headers.AcceptRanges.Add("bytes");
                    partialResponse.Headers.ETag = new EntityTagHeaderValue("\"" + hash + "\"");
                    var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                    partialResponse.Content = new ByteRangeStreamContent(stream, Request.Headers.Range, new MediaTypeHeaderValue("video/mp4"));

                    return(partialResponse);
                }
                catch (Exception ex)
                {
                    return(new HttpResponseMessage(HttpStatusCode.InternalServerError));
                }
            }
            else
            {
                return(new HttpResponseMessage(HttpStatusCode.RequestedRangeNotSatisfiable));
            }
        }
 internal override void AppendEncodedChars(char[] data, int offset, int size, Encoder encoder, bool flushEncoder) {
     int byteSize = encoder.GetBytes(data, offset, size, _data, _size-_free, flushEncoder);
     _free -= byteSize;
 }
示例#11
0
 /// <summary>
 /// Закодировать название
 /// </summary>
 /// <param name="encoder">Кодировщик</param>
 public void SetEncodedName(Encoder encoder)
 {
     char[] charArray = Name.ToCharArray();
     desc.fieldName = new byte[11];
     encoder.GetBytes(charArray, 0, charArray.Length, desc.fieldName, 0, true);
 }
示例#12
0
 internal override byte[] ObjectToBytes(object o, Encoder encoder)
 {
     byte[] res = new byte[empty.Length];
     Array.Copy(empty, res, empty.Length);
     if (o == null)
     {
         if (!Nullable)
             throw new Exception("Null value");
         return res;
     }
     string str = string.Empty;
     // Целочисленное со знаком
     if (o is SByte || o is Int16 || o is Int32 || o is Int64)
     {
         Int64 n = Convert.ToInt64(o);
         str = string.Format(formater, n);
     }
     // Целочисленное беззнаковое
     else if (o is Byte || o is UInt16 || o is UInt32 || o is UInt64)
     {
         UInt64 n = Convert.ToUInt64(o);
         str = string.Format(formater, n);
     }
     // С плавающей точкой
     else if (o is Single || o is Double)
     {
         Double n = Convert.ToDouble(o);
         str = string.Format(formater, n);
     }
     // decimal
     else if (o is Decimal)
     {
         Decimal n = Convert.ToDecimal(o);
         str = string.Format(formater, n);
     }
     else
         throw new Exception("Wrong type: number expected");
     str = str.Replace(",", ".");
     char[] charArray = str.ToCharArray();
     if (charArray.Length > sz)
         throw new Exception("Number too long. " + res.Length + " symbols expexted, " + charArray.Length + " symbols received: " + str);
     encoder.GetBytes(charArray, 0, Math.Min(charArray.Length, res.Length), res, 0, true);
     return res;
 }
		// try to encode some bytes at once with GetBytes
		private void EncoderFallbackExceptions_GetBytes (
			byte [] bytes,
			int testno,
			Encoder enc,
			EncoderFallbackExceptionTest t)
		{
			try {
				enc.GetBytes (
					t.str.ToCharArray (), 0, t.str.Length,
					bytes, 0, true);
				Assert.IsTrue (
					t.eindex.Length == 0,
					String.Format (
						"test#{0}-1: UNEXPECTED SUCCESS",
						testno));
			} catch(EncoderFallbackException ex) {
				Assert.IsTrue (
					t.eindex.Length > 0,
					String.Format (
						"test#{0}-1: UNEXPECTED FAIL",
						testno));
				Assert.IsTrue (
					ex.Index == t.eindex[0],
					String.Format (
						"test#{0}-1: Expected exception at {1} not {2}.",
						testno, t.eindex[0], ex.Index));
				Assert.IsTrue (
					!ex.IsUnknownSurrogate (),
					String.Format (
						"test#{0}-1: Expected false not {1} in IsUnknownSurrogate().",
						testno,
						ex.IsUnknownSurrogate ()));
				// NOTE: I know that in the previous check we
				// have asserted that ex.IsUnknownSurrogate()
				// is always false, but this does not mean that
				// we don't have to take in consideration its
				// real value for the next check.
				if (ex.IsUnknownSurrogate ())
					Assert.IsTrue (
						ex.CharUnknownHigh == t.str[ex.Index]
						&& ex.CharUnknownLow == t.str[ex.Index + 1],
						String.Format (
							"test#{0}-1: expected ({1:X}, {2:X}) not ({3:X}, {4:X}).",
							testno,
							t.str[ex.Index],
							t.str[ex.Index + 1],
							ex.CharUnknownHigh,
							ex.CharUnknownLow));
				else
					Assert.IsTrue (
						ex.CharUnknown == t.str[ex.Index],
						String.Format (
							"test#{0}-1: expected ({1:X}) not ({2:X}).",
							testno,
							t.str[ex.Index],
							ex.CharUnknown));
				enc.Reset ();
			}
		}
示例#14
0
    public void CreateTableClass(string tableName, string text)
    {
        string[][] textData = ReadDataFromText(text);
        Dictionary <string, string> typex00 = new Dictionary <string, string>()
        {
            { "vec", "Vector3" },
            { "int", "int" },
            { "float", "float" },
            { "str", "string" },
            { "note", "string" },
            { "describe", "string" }
        };

        Dictionary <string, string> .KeyCollection keys = typex00.Keys;
        for (int i = 0; i < textData[2].Length; i++)
        {
            bool isArray   = textData[2][i].Contains("[]");
            bool isArray2D = isArray ? textData[2][i].Contains("[][]") : false;
            foreach (string str in keys)
            {
                textData[2][i] = textData[2][i].ToLower().Contains(str) ? typex00[str] : textData[2][i];
            }
            textData[2][i] = isArray ? (textData[2][i] + "[]") : textData[2][i];
            textData[2][i] = isArray2D ? (textData[2][i] + "[]") : textData[2][i];
        }
        byte[] byData;
        char[] writeCharData;
        string needStringx00 = "using UnityEngine;using System.Collections;using System.Collections.Generic;\n";
        string needStringx01 = "public class ";
        string className     = tableName;
        string classDataName = className + "Data";
        string baseName      = ": ScriptableObject";
        string startSymbol   = "\n{\n";
        string needStringx02 = "\tpublic List <" + classDataName + "> table = new List<" + classDataName + ">() ;\n";
        string endSymbol     = "\n}\n";
        string baseNamex02   = "";
        string needStringx03 = "[System.Serializable]\npublic class " + classDataName + baseNamex02 + startSymbol;
        string properties    = "";
        string formater;

        for (int i = 0; i < textData[2].Length; i++)
        {
            string dataType   = textData[2][i].TrimEnd('\r');
            string dataOrigin = textData[1][i].TrimEnd('\r');
            if (textData[2][i].Contains("[][]"))
            {
                if (textData[2][i].Contains("int"))
                {
                    formater = "ReadInt32Array2D";
                }
                else if (textData[2][i].Contains("float"))
                {
                    formater = "ReadFloatArray2D";
                }
                else
                {
                    formater = "ReadStringArray2D";
                }
                properties += "\tpublic string s_" + dataOrigin + ";\n"
                              + "\tprivate " + dataType + dataOrigin + "_=null;\n"
                              + "\tpublic " + dataType + " " + dataOrigin + "{get{if(" + dataOrigin + "_==null)" + dataOrigin + "_=ysDataFormater." + formater + "(s_" + dataOrigin + ");return " + dataOrigin + "_;}set{}}\n";
            }
            else
            {
                properties += "\tpublic " + dataType + " " + dataOrigin + ";\n";
            }
        }
        properties.TrimEnd('\n');
        string writeString = needStringx00 + needStringx01 + className + baseName + startSymbol + needStringx02 + endSymbol + needStringx03 + properties + "}\n";

#if !UNITY_EDITOR_OSX
        writeString.Replace("\n", "\r\n");
#endif
        //string s_LastCreateClassText = writeString;
        using (FileStream fs = System.IO.File.Create(data.paths.classSccriptPath + tableName + ".cs"))
        {
            writeCharData = writeString.ToCharArray();
            byData        = new byte[writeCharData.Length];
            System.Text.Encoder e = System.Text.Encoding.UTF8.GetEncoder();
            e.GetBytes(writeCharData, 0, writeCharData.Length, byData, 0, true);
            fs.Seek(0, SeekOrigin.Begin);
            fs.Write(byData, 0, byData.Length);
            fs.Close();
        }
    }
示例#15
0
        internal override byte[] ObjectToBytes(object o, Encoder encoder)
        {
            byte[] res = new byte[empty.Length];
            Array.Copy(empty, res, empty.Length);
            if (o == null)
            {
                if (!Nullable)
                    throw new Exception("Null value");
                return res;
            }

            string text = (string)o;

            // 10 digits (bytes) representing a .DBT block number. The number is stored as a string, right justified and padded with blanks.
            long n = count;

            {
                // запись в dbt
                List<string> ss = new List<string>();
                if (text.Length == 0)
                {
                    ss.Add(string.Empty);
                }
                else
                {
                    int k = text.Length / 512;
                    int r = text.Length % 512;
                    for (int i = 0; i < k; i++)
                    {
                        ss.Add(text.Substring(512 * i, 512));
                    }
                    if (r > 0)
                    {
                        ss.Add(text.Substring(512 * k, r));
                    }
                }
                for (int i = 0; i < ss.Count; i++)
                {
                    char[] chars = ss[i].ToCharArray();
                    byte[] res2 = new byte[512];
                    encoder.GetBytes(chars, 0, Math.Min(chars.Length, res2.Length), res2, 0, true);
                    if (i == ss.Count - 1 && chars.Length < 512)
                    {
                        if (chars.Length <= 510)
                        {
                            res2[chars.Length] = (byte)0x1A;
                            res2[chars.Length + 1] = (byte)0x1A;
                        }
                        else
                        {
                            res2[chars.Length] = (byte)0x1A;
                        }
                    }
                    stream.Write(res2, 0, 512);
                }
                count += ss.Count;
            }

            string str = string.Empty;
            str = string.Format(formater, n);
            str = str.Replace(",", ".");
            char[] charArray = str.ToCharArray();
            if (charArray.Length > size)
                throw new Exception("Memo address too long. " + res.Length + " symbols expexted, " + charArray.Length + " symbols received: " + str);
            encoder.GetBytes(charArray, 0, Math.Min(charArray.Length, res.Length), res, 0, true);
            return res;
        }
示例#16
0
        static bool GetNextValue(string charset, Encoder encoder, HexEncoder hex, char[] chars, ref int index,
		                          ref byte[] bytes, ref byte[] encoded, int maxLength, out string value)
        {
            int length = chars.Length - index;

            if (length < maxLength) {
                switch (GetEncodeMethod (chars, index, length)) {
                case EncodeMethod.Quote:
                    value = MimeUtils.Quote (new string (chars, index, length));
                    index += length;
                    return false;
                case EncodeMethod.None:
                    value = new string (chars, index, length);
                    index += length;
                    return false;
                }
            }

            length = Math.Min (maxLength, length);
            int ratio, count, n;

            do {
                count = encoder.GetByteCount (chars, index, length, true);
                if (count > maxLength && length > 1) {
                    ratio = (int) Math.Round ((double) count / (double) length);
                    length -= Math.Max ((count - maxLength) / ratio, 1);
                    continue;
                }

                if (bytes.Length < count)
                    Array.Resize<byte> (ref bytes, count);

                count = encoder.GetBytes (chars, index, length, bytes, 0, true);

                // Note: the first chunk needs to be encoded in order to declare the charset
                if (index > 0 || charset == "us-ascii") {
                    var method = GetEncodeMethod (bytes, count);

                    if (method == EncodeMethod.Quote) {
                        value = MimeUtils.Quote (Encoding.ASCII.GetString (bytes, 0, count));
                        index += length;
                        return false;
                    }

                    if (method == EncodeMethod.None) {
                        value = Encoding.ASCII.GetString (bytes, 0, count);
                        index += length;
                        return false;
                    }
                }

                n = hex.EstimateOutputLength (count);
                if (encoded.Length < n)
                    Array.Resize<byte> (ref encoded, n);

                // only the first value gets a charset declaration
                int charsetLength = index == 0 ? charset.Length + 2 : 0;

                n = hex.Encode (bytes, 0, count, encoded);
                if (n > 3 && (charsetLength + n) > maxLength) {
                    int x = 0;

                    for (int i = n - 1; i >= 0 && charsetLength + i >= maxLength; i--) {
                        if (encoded[i] == (byte) '%')
                            x--;
                        else
                            x++;
                    }

                    ratio = (int) Math.Round ((double) count / (double) length);
                    length -= Math.Max (x / ratio, 1);
                    continue;
                }

                if (index == 0)
                    value = charset + "''" + Encoding.ASCII.GetString (encoded, 0, n);
                else
                    value = Encoding.ASCII.GetString (encoded, 0, n);
                index += length;
                return true;
            } while (true);
        }
示例#17
0
        // We pass in private instance fields of this MarshalByRefObject-derived type as local params
        // to ensure performant access inside the state machine that corresponds this async method.
        private static async Task FlushAsyncInternal(StreamWriter _this, bool flushStream, bool flushEncoder,
                                                     char[] charBuffer, int charPos, bool haveWrittenPreamble,
                                                     Encoding encoding, Encoder encoder, Byte[] byteBuffer, Stream stream)
        {
            if (!haveWrittenPreamble)
            {
                _this.HaveWrittenPreamble_Prop = true;
                byte[] preamble = encoding.GetPreamble();
                if (preamble.Length > 0)
                {
                    await stream.WriteAsync(preamble, 0, preamble.Length).ConfigureAwait(false);
                }
            }

            int count = encoder.GetBytes(charBuffer, 0, charPos, byteBuffer, 0, flushEncoder);
            if (count > 0)
            {
                await stream.WriteAsync(byteBuffer, 0, count).ConfigureAwait(false);
            }

            // By definition, calling Flush should flush the stream, but this is
            // only necessary if we passed in true for flushStream.  The Web
            // Services guys have some perf tests where flushing needlessly hurts.
            if (flushStream)
            {
                await stream.FlushAsync().ConfigureAwait(false);
            }
        }
        private unsafe static int UnsafeAppendEncodedChars(char[] src, int srcOffset, int srcSize, IntPtr dest, int destOffset, int destSize, Encoder encoder, bool flushEncoder) {
            int numBytes = 0;

            byte* destBytes = ((byte*)dest) + destOffset;

            fixed (char* charSrc = src) {
                numBytes = encoder.GetBytes(charSrc+srcOffset, srcSize, destBytes, destSize, flushEncoder);
            }

            return numBytes;
        }
示例#19
0
 internal override byte[] ObjectToBytes(object o, Encoder encoder)
 {
     byte[] res = new byte[empty.Length];
     Array.Copy(empty, res, empty.Length);
     if (o == null)
     {
         if (!Nullable)
             throw new Exception("Null value");
         return res;
     }
     if (!(o is string))
         throw new Exception("Wrong type: string expected");
     string str = (string)o;
     char[] charArray = str.ToCharArray();
     if (!truncate && charArray.Length > res.Length)
         throw new Exception("String too long. " + res.Length + " symbols expexted, " + charArray.Length + " symbols received: " + str);
     encoder.GetBytes(charArray, 0, Math.Min(charArray.Length, res.Length), res, 0, true);
     return res;
 }
        internal override void AppendEncodedChars(char[] data, int offset, int size, System.Text.Encoder encoder, bool flushEncoder)
        {
            int num = encoder.GetBytes(data, offset, size, this._data, base._size - base._free, flushEncoder);

            base._free -= num;
        }
示例#21
0
 internal override byte[] ObjectToBytes(object o, Encoder encoder)
 {
     byte[] res = new byte[1];
     if (o == null)
     {
         if (!Nullable)
             throw new Exception("Null value");
         encoder.GetBytes(Null, 0, 1, res, 0, true);
         return res;
     }
     if (!(o is bool))
         throw new Exception("Wrong type: bool expected");
     bool b = (bool)o;
     encoder.GetBytes(b ? Y : N, 0, 1, res, 0, true);
     return res;
 }
        // WOS 1926509: ASP.NET:  WriteSubstitution in integrated mode needs to support callbacks that return String.Empty
        private unsafe void CreateFirstSubstData(String s, IIS7WorkerRequest iis7WorkerRequest, Encoder encoder) {
            Debug.Assert(s != null, "s != null");

            IntPtr pbBuffer;
            int numBytes = 0;
            int cch = s.Length;
            if (cch > 0) {
                fixed (char * pch = s) {
                    int cbBuffer = encoder.GetByteCount(pch, cch, true /*flush*/);
                    pbBuffer = iis7WorkerRequest.AllocateRequestMemory(cbBuffer);
                    if (pbBuffer != IntPtr.Zero) {
                        numBytes = encoder.GetBytes(pch, cch, (byte*)pbBuffer, cbBuffer, true /*flush*/);
                    }
                }
            }
            else {
                // deal with empty string
                pbBuffer = iis7WorkerRequest.AllocateRequestMemory(1);
            }

            if (pbBuffer == IntPtr.Zero) {
                throw new OutOfMemoryException();
            }
            _firstSubstData = pbBuffer;
            _firstSubstDataSize = numBytes;
        }
 public static int GetBytes(Encoder encoder, ReadOnlySpan <char> input, Span <byte> output, bool flush) => encoder.GetBytes(input, output, flush);
 /// <summary>
 /// Gets the encoded bytes as a Memory from a character Span
 /// </summary>
 /// <param name="encoder">The encoder performing the encoding operation</param>
 /// <param name="input">The input characters</param>
 /// <param name="output">The span that receives the output</param>
 /// <param name="flush">True to flush the encoder, otherwise False</param>
 /// <returns>The number of bytes written</returns>
 public static unsafe int GetBytes(this Encoder encoder, ReadOnlySpan <char> input, Span <byte> output, bool flush)
 {
     fixed(char *pInput = &MemoryMarshal.GetReference(input))
     fixed(byte *pOutput = &MemoryMarshal.GetReference(output))
     return(encoder.GetBytes(pInput, input.Length, pOutput, output.Length, flush));
 }
示例#25
0
 internal override byte[] ObjectToBytes(object o, Encoder encoder)
 {
     if (o == null)
     {
         if (!Nullable)
             throw new Exception("Null value");
         return empty;
     }
     if (!(o is DateTime))
         throw new Exception("Wrong type: date expected");
     DateTime dt = (DateTime)o;
     // YYYYMMDD
     byte[] res = new byte[8];
     string str = dt.ToString("yyyyMMdd");
     encoder.GetBytes(str.ToCharArray(), 0, 8, res, 0, true);
     return res;
 }