C#中如何将字符串转换byte[],同时如何将byte[]换成字符串?
时间:2011-04-25 来源:seoxs
C#中如何将字符串转换byte[],同时如何将byte[]换成字符串!
1 string to byte []
string str = "abcd" ;
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(str);
-------------------------------------------------------------------------------------------------------------
2 byte[] to string
byte[] bytes = new byte[255] ;
string str = System.Text.Encoding.ASCII.GetString(bytes,0,bytes.Length);
--------------------------------------------------------------------------------------------
在附上二个方法:
private static byte[] HexStringToByteArray(string s){
s = s.Replace(" ", "");
byte[] buffer = new byte[s.Length / 2];
for (int i = 0; i < s.Length; i += 2)
buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);
return buffer;
}
///
///www.elivn.com
private string ByteArrayToHexString(byte[] data)
{
StringBuilder sb = new StringBuilder(data.Length * 3);
foreach (byte b in data)
sb.Append(Convert.ToString(b, 16).PadLeft(2, '0').PadRight(3, ' '));
return sb.ToString().ToUpper();
}