C# string和byte[]的轉換

C# string和byte[]的轉換

C# string和byte[]的轉換


 


資料來源:http://isanhsu.blogspot.tw/2012/03/stringbyte-c.html

 


01.string類型轉成byte[]

  byte[] byteArray = System.Text.Encoding.Default.GetBytes ( str );

 

02.byte[]轉成string

  string str = System.Text.Encoding.Default.GetString ( byteArray );

 

03.16進制陣列轉字串 

        public static string ToHexString(byte[] bytes)
        {
            string hexString = string.Empty;
            if (bytes != null)
            {
                StringBuilder str = new StringBuilder();

                for (int i = 0; i < bytes.Length; i++)
                {
                    str.Append(bytes[i].ToString("X2"));
                }
                hexString = str.ToString();
            }
            return hexString;
        }

 

03.字串轉16進制陣列

        public static byte[] GetBytes(string HexString)
        {
            int byteLength = HexString.Length / 2;
            byte[] bytes = new byte[byteLength];
            string hex;
            int j = 0;
            for (int i = 0; i < bytes.Length; i++)
            {
                hex = new String(new Char[] { HexString[j], HexString[j + 1] });
                bytes[i] = HexToByte(hex);
                j = j + 2;
            }
            return bytes;
        }
        public static byte HexToByte(string hex)
        {
            if (hex.Length > 2 || hex.Length <= 0)
                throw new ArgumentException("hex must be 1 or 2 characters in length");
            byte newByte = byte.Parse(hex, System.Globalization.NumberStyles.HexNumber);
            return newByte;
        }

 

 

C# 中文 String byte 互轉

byte[] UTF8bytes = Encoding.UTF8.GetBytes(str);
string UTF8String = Encoding.UTF8.GetString(UTF8bytes);

byte[] ASCIIbytes = Encoding.ASCII.GetBytes(str);
string ASCIIString = Encoding.ASCII.GetString(ASCIIbytes);

byte[] Dbyte = System.Text.Encoding.Default.GetBytes(str);
string Dstring = System.Text.Encoding.Default.GetString(Dbyte);

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *