Four methods C # byte [] turn string, string transfer byte [] of

 

 

Reprinted: https: //blog.csdn.net/tom_221x/article/details/71643015

The first

  1. string  str    = System.Text.Encoding.UTF8.GetString(bytes);
  2. byte[] decBytes = System.Text.Encoding.UTF8.GetBytes(str);

The same, System.Text.Encoding.Default, System.Text.Encoding.ASCII also possible. It may also be used System.Text.Encoding.UTF8.GetString (bytes) .TrimEnd ( '\ 0') to the end of the string with the identification.

 

The second

  1. string    str    = BitConverter.ToString(bytes); 
  2. String[] tempArr = str.Split('-');
  3. byte[]   decBytes = new byte[tempArr.Length];
  4. for (int i = 0; i < tempArr.Length; i++)
  5. {
  6.     decBytes[i] = Convert.ToByte(tempArr[i], 16);
  7. }

This method will add the string '-' hyphen, and there is no function converts back. It needs to be converted manually bytes.

 

The third

  1. string str      = Convert.ToBase64String(bytes); 
  2. byte[] decBytes = Convert.FromBase64String(str);

This method is simple and clear, perfect, no problem. It is noted that, out of the converted string may contain '+', '/', '=' if it is as url addresses, required encode.

Fourth

  1. string  str    = HttpServerUtility.UrlTokenEncode(bytes); 
  2. byte[] decBytes = HttpServerUtility.UrlTokenDecode(str);

This method will automatically encode url address special characters can be directly used as the url address to use. But need to rely on System.Web library to use.

 

Guess you like

Origin www.cnblogs.com/wfy680/p/12004512.html