标签:style blog color os ar for sp div on
C# string byte数组转换之string类型转成byte[]:
byte[] byteArray = System.Text.Encoding.Default.GetBytes ( str );
反过来,byte[]转成string:
string str = System.Text.Encoding.Default.GetString ( byteArray );
其它编码方式的,如System.Text.UTF8Encoding,System.Text.UnicodeEncoding class等
有时候还有这样一些需求: byte[] 转成原16进制格式的string,例如0xae00cf, 转换成 "ae00cf";
new byte[]{ 0x30, 0x31}转成"3031":
1 public static string ToHexString(byte[] bytes) // 0xae00cf => "AE00CF " ? 2 { 3 string HexString = string.Empty; 4 if (bytes != null) 5 { 6 StringBuilder builder = new StringBuilder(); 7 for (int i = 0; i < bytes.Length; i++) 8 { 9 builder.Append(bytes[i].ToString("X2")); 10 } 11 HexString = builder.ToString(); 12 } 13 return HexString; 14 } 15 16 // 把字节型转换成十六进制字符串 17 public static string ByteToString(byte[] InBytes) 18 { 19 string StringOut = ""; 20 foreach (byte InByte in InBytes) 21 { 22 StringOut = StringOut + String.Format("{0:X2} ", InByte); 23 } 24 return StringOut; 25 } 26 public string ByteToString(byte[] InBytes, int len) 27 { 28 string StringOut = ""; 29 for (int i = 0; i < len; i++) 30 { 31 StringOut = StringOut + String.Format("{0:X2} ", InBytes[i]); 32 } 33 return StringOut; 34 } 35 // 把十六进制字符串转换成字节型 36 public static byte[] StringToByte(string InString) 37 { 38 string[] ByteStrings; 39 ByteStrings = InString.Split(" ".ToCharArray()); 40 byte[] ByteOut; 41 ByteOut = new byte[ByteStrings.Length - 1]; 42 for (int i = 0; i == ByteStrings.Length - 1; i++) 43 { 44 ByteOut[i] = Convert.ToByte(("0x" + ByteStrings[i])); 45 } 46 return ByteOut; 47 } 48 49 50 //得到十六进制的string数组 51 private static string[] HexToStringArray(byte[] bytes) 52 { 53 string[] strs = new string[bytes.Length]; 54 55 for (int i = 0; i < bytes.Length; i++) 56 { 57 strs[i] = Convert.ToString(bytes[i], 16); 58 } 59 return strs; 60 }
标签:style blog color os ar for sp div on
原文地址:http://www.cnblogs.com/wlmLinker/p/4060186.html