首页 > 代码库 > C# string byte转换
C# string byte转换
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 }
C# string byte转换
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。