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


C# Encoding.GetBytes方法代码示例

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


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

示例1: GetBytes

        public static void GetBytes(Encoding encoding, string source, int index, int count, byte[] bytes, int byteIndex, byte[] expectedBytes)
        {
            byte[] originalBytes = (byte[])bytes.Clone();

            if (index == 0 && count == source.Length)
            {
                // Use GetBytes(string)
                byte[] stringResultBasic = encoding.GetBytes(source);
                VerifyGetBytes(stringResultBasic, 0, stringResultBasic.Length, originalBytes, expectedBytes);

                // Use GetBytes(char[])
                byte[] charArrayResultBasic = encoding.GetBytes(source.ToCharArray());
                VerifyGetBytes(charArrayResultBasic, 0, charArrayResultBasic.Length, originalBytes, expectedBytes);
            }
            // Use GetBytes(char[], int, int)
            byte[] charArrayResultAdvanced = encoding.GetBytes(source.ToCharArray(), index, count);
            VerifyGetBytes(charArrayResultAdvanced, 0, charArrayResultAdvanced.Length, originalBytes, expectedBytes);

            // Use GetBytes(string, int, int, byte[], int)
            byte[] stringBytes = (byte[])bytes.Clone();
            int stringByteCount = encoding.GetBytes(source, index, count, stringBytes, byteIndex);
            VerifyGetBytes(stringBytes, byteIndex, stringByteCount, originalBytes, expectedBytes);
            Assert.Equal(expectedBytes.Length, stringByteCount);

            // Use GetBytes(char[], int, int, byte[], int)
            byte[] charArrayBytes = (byte[])bytes.Clone();
            int charArrayByteCount = encoding.GetBytes(source.ToCharArray(), index, count, charArrayBytes, byteIndex);
            VerifyGetBytes(charArrayBytes, byteIndex, charArrayByteCount, originalBytes, expectedBytes);
            Assert.Equal(expectedBytes.Length, charArrayByteCount);
        }
开发者ID:Dmitry-Me,项目名称:corefx,代码行数:30,代码来源:EncodingTestHelpers.cs

示例2: GetBytes

        public static void GetBytes(Encoding encoding, string source, int index, int count, byte[] bytes, int byteIndex, int expected)
        {
            // Use GetBytes(string, int, int, byte[], int)
            byte[] stringBytes = (byte[])bytes.Clone();
            int stringResult = encoding.GetBytes(source, index, count, stringBytes, byteIndex);
            Assert.Equal(expected, stringResult);

            // Use GetBytes(char[], int, int, byte[], int)
            byte[] charArrayBytes = (byte[])bytes.Clone();
            int charArrayResult = encoding.GetBytes(source, index, count, charArrayBytes, byteIndex);
            Assert.Equal(expected, charArrayResult);
        }
开发者ID:eerhardt,项目名称:corefx,代码行数:12,代码来源:EncodingTestHelpers.cs

示例3: VerifyGetBytes

        private static unsafe void VerifyGetBytes(Encoding encoding, string source, int index, int count, byte[] bytes, int byteIndex, byte[] expectedBytes)
        {
            byte[] originalBytes = (byte[])bytes.Clone();

            if (index == 0 && count == source.Length)
            {
                // Use GetBytes(string)
                byte[] stringResultBasic = encoding.GetBytes(source);
                VerifyGetBytes(stringResultBasic, 0, stringResultBasic.Length, originalBytes, expectedBytes);

                // Use GetBytes(char[])
                byte[] charArrayResultBasic = encoding.GetBytes(source.ToCharArray());
                VerifyGetBytes(charArrayResultBasic, 0, charArrayResultBasic.Length, originalBytes, expectedBytes);
            }
            // Use GetBytes(char[], int, int)
            byte[] charArrayResultAdvanced = encoding.GetBytes(source.ToCharArray(), index, count);
            VerifyGetBytes(charArrayResultAdvanced, 0, charArrayResultAdvanced.Length, originalBytes, expectedBytes);

            // Use GetBytes(string, int, int, byte[], int)
            byte[] stringBytes = (byte[])bytes.Clone();
            int stringByteCount = encoding.GetBytes(source, index, count, stringBytes, byteIndex);
            VerifyGetBytes(stringBytes, byteIndex, stringByteCount, originalBytes, expectedBytes);
            Assert.Equal(expectedBytes.Length, stringByteCount);

            // Use GetBytes(char[], int, int, byte[], int)
            byte[] charArrayBytes = (byte[])bytes.Clone();
            int charArrayByteCount = encoding.GetBytes(source.ToCharArray(), index, count, charArrayBytes, byteIndex);
            VerifyGetBytes(charArrayBytes, byteIndex, charArrayByteCount, originalBytes, expectedBytes);
            Assert.Equal(expectedBytes.Length, charArrayByteCount);

            // Use GetBytes(char*, int, byte*, int) - only works for non-null/non-empty char* or byte*
            if (expectedBytes.Length > 0)
            {
                byte[] charPointerBytes = (byte[])bytes.Clone();
                fixed (char* pChars = source.ToCharArray())
                fixed (byte* pBytes = charPointerBytes)
                {
                    int charPointerByteCount = encoding.GetBytes(pChars + index, count, pBytes + byteIndex, charPointerBytes.Length - byteIndex);
                    Assert.Equal(expectedBytes.Length, charPointerByteCount);
                }
                VerifyGetBytes(charPointerBytes, byteIndex, charArrayByteCount, originalBytes, expectedBytes);
            }
        }
开发者ID:ChuangYang,项目名称:corefx,代码行数:43,代码来源:EncodingTestHelpers.cs

示例4: TestEncoding

 private void TestEncoding(Encoding enc, int byteCount, int maxByteCount, byte[] bytes)
 {
     Assert.Equal(byteCount, enc.GetByteCount(s_myChars));
     Assert.Equal(maxByteCount, enc.GetMaxByteCount(s_myChars.Length));
     Assert.Equal(enc.GetBytes(s_myChars), bytes);
     Assert.Equal(enc.GetCharCount(bytes), s_myChars.Length);
     Assert.Equal(enc.GetChars(bytes), s_myChars);
     Assert.Equal(enc.GetString(bytes, 0, bytes.Length), s_myString);
     Assert.NotEqual(0, enc.GetHashCode());
 }
开发者ID:noahfalk,项目名称:corefx,代码行数:10,代码来源:ConvertUnicodeEncodings.cs

示例5: GetHash

    public static byte[] GetHash(string input, Encoding encoding)
    {
        if (null == input)
            throw new System.ArgumentNullException("input", "Unable to calculate hash over null input data");
        if (null == encoding)
            throw new System.ArgumentNullException("encoding", "Unable to calculate hash over a string without a default encoding. Consider using the GetHash(string) overload to use UTF8 Encoding");

        byte[] target = encoding.GetBytes(input);

        return GetHash(target);
    }
开发者ID:1mahesh,项目名称:LeaderboardsSDK,代码行数:11,代码来源:MD5.cs

示例6: CompressGZip

 /// <summary>
 ///     A string extension method that compress the given string to GZip byte array.
 /// </summary>
 /// <param name="this">The stringToCompress to act on.</param>
 /// <param name="encoding">The encoding.</param>
 /// <returns>The string compressed into a GZip byte array.</returns>
 public static byte[] CompressGZip(this string @this, Encoding encoding)
 {
     byte[] stringAsBytes = encoding.GetBytes(@this);
     using (var memoryStream = new MemoryStream())
     {
         using (var zipStream = new GZipStream(memoryStream, CompressionMode.Compress))
         {
             zipStream.Write(stringAsBytes, 0, stringAsBytes.Length);
             zipStream.Close();
             return (memoryStream.ToArray());
         }
     }
 }
开发者ID:ChuangYang,项目名称:Z.ExtensionMethods,代码行数:19,代码来源:String.CompressGZip.cs

示例7: Save

 public int Save(string path, string dat,Encoding encode)
 {
     try
     {
         FileStream fs = new FileStream(Application.persistentDataPath + "/" + path, FileMode.Create, FileAccess.Write);
         BinaryWriter sw = new BinaryWriter(fs);
         var bin = aes.Encrypt(encode.GetBytes(dat));
         sw.Write(bin);
         sw.Flush();
         sw.Close();
     }
     catch {
         // セーブ失敗
         return -1;
     }
     return 0;
 }
开发者ID:GotoK,项目名称:H401,代码行数:17,代码来源:FileLoader.cs

示例8: Decrypt3DES

    ///   <summary>   
    ///   3des解密字符串   
    ///   </summary>   
    ///   <param   name="a_strString">要解密的字符串</param>   
    ///   <param   name="a_strKey">密钥</param>   
    ///   <param   name="encoding">编码方式</param>   
    ///   <returns>解密后的字符串</returns>   
    ///   <exception   cref="">密钥错误</exception>   
    ///   <remarks>静态方法,指定编码方式</remarks>   
    public string Decrypt3DES(string a_strString, string a_strKey, Encoding encoding)
    {
        TripleDESCryptoServiceProvider DES = new TripleDESCryptoServiceProvider();
        MD5CryptoServiceProvider hashMD5 = new MD5CryptoServiceProvider();

        DES.Key = hashMD5.ComputeHash(encoding.GetBytes(a_strKey));
        DES.Mode = CipherMode.ECB;

        ICryptoTransform DESDecrypt = DES.CreateDecryptor();

        string result = "";
        try {
            byte[] Buffer = Convert.FromBase64String(a_strString);
            result = encoding.GetString(DESDecrypt.TransformFinalBlock
            (Buffer, 0, Buffer.Length));
        } catch (Exception e) {
        #if   DEBUG
          Console.WriteLine("错误:{0}"   ,   e)   ;
        #endif//DEBUG
            throw (new Exception("不是有效的 base64  字符串", e));
        }

        return result;
    }
开发者ID:EdgarEDT,项目名称:myitoppsp,代码行数:33,代码来源:EncryptString.cs

示例9: CreatePostHttpResponse

    //---------------------------------------以下代码请勿更动---------------------------------------------------------------------------------------------
    /// <summary>  
    /// 创建POST方式的HTTP请求  
    /// </summary>  
    /// <param name="url">请求的URL</param>  
    /// <param name="parameters">随同请求POST的参数名称及参数值字典</param>  
    /// <param name="timeout">请求的超时时间</param>  
    /// <param name="userAgent">请求的客户端浏览器信息,可以为空</param>  
    /// <param name="requestEncoding">发送HTTP请求时所用的编码</param>  
    /// <param name="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param>  
    /// <returns></returns>  
    public static HttpWebResponse CreatePostHttpResponse(string url,IDictionary<string,string> parameters,int timeout, string userAgent,Encoding requestEncoding,CookieCollection cookies)
    {
        if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }
            if(requestEncoding==null)
            {
                throw new ArgumentNullException("requestEncoding");
            }
            HttpWebRequest request=null;
            request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            if (!string.IsNullOrEmpty(userAgent))
            {
                request.UserAgent = userAgent;
            }
            else
            {
                request.UserAgent = DefaultUserAgent;
            }

            if (timeout!=null)
            {
                request.Timeout = timeout;
            }
            if (cookies != null)
            {
                request.CookieContainer = new CookieContainer();
                request.CookieContainer.Add(cookies);
            }
            //如果需要POST数据
            if(!(parameters==null||parameters.Count==0))
            {
                StringBuilder buffer = new StringBuilder();
                int i = 0;
                foreach (string key in parameters.Keys)
                {
                    if (i > 0)
                    {
                        buffer.AppendFormat("&{0}={1}", key, parameters[key]);
                    }
                    else
                    {
                        buffer.AppendFormat("{0}={1}", key, parameters[key]);
                    }
                    i++;
                }
                byte[] data = requestEncoding.GetBytes(buffer.ToString());
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            return request.GetResponse() as HttpWebResponse;
    }
开发者ID:test-lin,项目名称:Utility-class,代码行数:69,代码来源:orderQueryResult.aspx.cs

示例10: UrlEncodeToBytes

 public static byte[] UrlEncodeToBytes(string str, Encoding e)
 {
     if (str == null)
         return (byte[])null;
     byte[] bytes = e.GetBytes(str);
     return UrlEncode(bytes, 0, bytes.Length, false);
 }
开发者ID:gramcha,项目名称:XFeatures,代码行数:7,代码来源:XFeaturesPackage.cs

示例11: ValidateConsoleEncoding

    public static unsafe void ValidateConsoleEncoding(Encoding encoding)
    {
        Assert.NotNull(encoding);
        // The primary purpose of ConsoleEncoding is to return an empty preamble.
        Assert.Equal(Array.Empty<byte>(), encoding.GetPreamble());

        // There's not much validation we can do, but we can at least invoke members
        // to ensure they don't throw exceptions as they delegate to the underlying
        // encoding wrapped by ConsoleEncoding.

        Assert.False(string.IsNullOrWhiteSpace(encoding.EncodingName));
        Assert.False(string.IsNullOrWhiteSpace(encoding.WebName));
        Assert.True(encoding.CodePage >= 0);
        bool ignored = encoding.IsSingleByte;

        // And we can validate that the encoding is self-consistent by roundtripping
        // data between chars and bytes.

        string str = "This is the input string.";
        char[] strAsChars = str.ToCharArray();
        byte[] strAsBytes = encoding.GetBytes(str);
        Assert.Equal(strAsBytes.Length, encoding.GetByteCount(str));
        Assert.True(encoding.GetMaxByteCount(str.Length) >= strAsBytes.Length);

        Assert.Equal(str, encoding.GetString(strAsBytes));
        Assert.Equal(str, encoding.GetString(strAsBytes, 0, strAsBytes.Length));
        Assert.Equal(str, new string(encoding.GetChars(strAsBytes)));
        Assert.Equal(str, new string(encoding.GetChars(strAsBytes, 0, strAsBytes.Length)));
        fixed (byte* bytesPtr = strAsBytes)
        {
            char[] outputArr = new char[encoding.GetMaxCharCount(strAsBytes.Length)];

            int len = encoding.GetChars(strAsBytes, 0, strAsBytes.Length, outputArr, 0);
            Assert.Equal(str, new string(outputArr, 0, len));
            Assert.Equal(len, encoding.GetCharCount(strAsBytes));
            Assert.Equal(len, encoding.GetCharCount(strAsBytes, 0, strAsBytes.Length));

            fixed (char* charsPtr = outputArr)
            {
                len = encoding.GetChars(bytesPtr, strAsBytes.Length, charsPtr, outputArr.Length);
                Assert.Equal(str, new string(charsPtr, 0, len));
                Assert.Equal(len, encoding.GetCharCount(bytesPtr, strAsBytes.Length));
            }

            Assert.Equal(str, encoding.GetString(bytesPtr, strAsBytes.Length));
        }

        Assert.Equal(strAsBytes, encoding.GetBytes(strAsChars));
        Assert.Equal(strAsBytes, encoding.GetBytes(strAsChars, 0, strAsChars.Length));
        Assert.Equal(strAsBytes.Length, encoding.GetByteCount(strAsChars));
        Assert.Equal(strAsBytes.Length, encoding.GetByteCount(strAsChars, 0, strAsChars.Length));
        fixed (char* charsPtr = strAsChars)
        {
            Assert.Equal(strAsBytes.Length, encoding.GetByteCount(charsPtr, strAsChars.Length));

            byte[] outputArr = new byte[encoding.GetMaxByteCount(strAsChars.Length)];
            Assert.Equal(strAsBytes.Length, encoding.GetBytes(strAsChars, 0, strAsChars.Length, outputArr, 0));
            fixed (byte* bytesPtr = outputArr)
            {
                Assert.Equal(strAsBytes.Length, encoding.GetBytes(charsPtr, strAsChars.Length, bytesPtr, outputArr.Length));
            }
            Assert.Equal(strAsBytes.Length, encoding.GetBytes(str, 0, str.Length, outputArr, 0));
        }
    }
开发者ID:ESgarbi,项目名称:corefx,代码行数:64,代码来源:ReadAndWrite.cs

示例12: UrlEncode

		public static string UrlEncode (string s, Encoding Enc)
		{
			if (s == null)
				return null;

			if (s == String.Empty)
				return String.Empty;

			bool needEncode = false;
			int len = s.Length;
			for (int i = 0; i < len; i++) {
				char c = s [i];
				if ((c < '0') || (c < 'A' && c > '9') || (c > 'Z' && c < 'a') || (c > 'z')) {
					if (HttpEncoderFromMono.NotEncoded (c))
						continue;

					needEncode = true;
					break;
				}
			}

			if (!needEncode)
				return s;

			// avoided GetByteCount call
			byte [] bytes = new byte[Enc.GetMaxByteCount(s.Length)];
			int realLen = Enc.GetBytes (s, 0, s.Length, bytes, 0);
			return Encoding.ASCII.GetString (UrlEncodeToBytes (bytes, 0, realLen));
		}
开发者ID:jwickberg,项目名称:libpalaso,代码行数:29,代码来源:HttpUtilityFromMono.cs

示例13: GetBytes

	public static byte[] GetBytes(this String This, Encoding Encoding)
	{
		return Encoding.GetBytes(This);
	}
开发者ID:soywiz,项目名称:csharputils,代码行数:4,代码来源:StringExtensions.cs

示例14: GetSBytesForEncoding

 private static sbyte[] GetSBytesForEncoding(Encoding encoding, string s)
 {
     var sbytes = new sbyte[encoding.GetByteCount(s)];
     encoding.GetBytes(s, 0, s.Length, (byte[]) (object) sbytes, 0);
     return sbytes;
 }
开发者ID:shayhatsor,项目名称:curator,代码行数:6,代码来源:StringHelperClass.cs

示例15: WriteHashtable

 private static void WriteHashtable(MemoryStream stream, Hashtable h, Hashtable ht, ref int hv, Encoding encoding)
 {
     int len = h.Count;
     byte[] hlen = Encoding.ASCII.GetBytes(len.ToString());
     stream.WriteByte(__a);
     stream.WriteByte(__Colon);
     stream.Write(hlen, 0, hlen.Length);
     stream.WriteByte(__Colon);
     stream.WriteByte(__LeftB);
     foreach (DictionaryEntry entry in h)
     {
         if ((entry.Key is Byte) || (entry.Key is SByte) || (entry.Key is Int16) || (entry.Key is UInt16) || (entry.Key is Int32))
         {
             WriteInteger(stream, Encoding.ASCII.GetBytes(entry.Key.ToString()));
         }
         else if (entry.Key is Boolean)
         {
             WriteInteger(stream, new byte[] { ((Boolean)entry.Key) ? __1 : __0 });
         }
         else
         {
             WriteString(stream, encoding.GetBytes(entry.Key.ToString()));
         }
         Serialize(stream, entry.Value, ht, ref hv, encoding);
     }
     stream.WriteByte(__RightB);
 }
开发者ID:wenysky,项目名称:deepinsummer,代码行数:27,代码来源:PHPSerializer.cs


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