高效byte[]和string互转的方法

public static class Utils
    {
        
/// <summary>
        
/// 普通方法——字节数组转字符串,最容易想到
        
/// </summary>
        
/// <param name="input"></param>
        
/// <returns></returns>
        public static string BytesToString(byte[] input)
        {
            StringBuilder sb 
= new StringBuilder();
            
foreach (byte b in input)
            {
                sb.Append(b.ToString(
"X2"));
            }
            
return sb.ToString();
        }

        
/// <summary>
        
/// 高效的字节数组转字符串
        
/// </summary>
        
/// <param name="input"></param>
        
/// <returns></returns>
        public static string BytesToStringH(byte[] input)
        {
            
int len = input.Length;
            
char[] chars = new char[len * 2];
            
for (int i = 0; i < len; i++)
            {
                chars[i 
* 2= IntToChar(input[i] >> 4);
                chars[i 
* 2 + 1= IntToChar(input[i] & 15);
            }
            
return new string(chars);
        }
        
/// <summary>
        
/// 使用指针效率最高
        
/// </summary>
        
/// <param name="input"></param>
        
/// <returns></returns>
        public static unsafe string BytesToStringS(byte[] input)
        {
            
int len = input.Length;
            
char[] chars = new char[len * 2];
            
fixed (char* lchars = chars)
            {
                
fixed (byte* linput = input)
                {
                    
char* pchar = lchars;
                    
byte* pbyte = linput;
                    
for (int i = 0; i < len; i++)
                    {
                        
*pchar = IntToChar(*pbyte >> 4);
                        pchar
++;
                        
*pchar = IntToChar(*pbyte & 15);
                        pchar
++;
                        pbyte
++;
                    }
                }
            }
            
return new string(chars);
        }

        
/// <summary>
        
/// 普通方法——字符串转字节数组,最容易想到
        
/// </summary>
        
/// <param name="input"></param>
        
/// <returns></returns>
        public static byte[] StringToBytes(string input)
        {
            
int len = input.Length;
            
if (len % 2 != 0)
            {
                
throw new Exception("输入的字符串长度有误,必须是偶数。");
            }
            
byte[] bytes = new byte[len / 2];
            
for (int i = 0; i < len / 2; i++)
            {
                
if (!byte.TryParse(input.Substring(i * 22), System.Globalization.NumberStyles.HexNumber, nullout bytes[i]))
                {
                    
throw new Exception(string.Format("在位置{0}处的字符无法转换为16进制字节", i * 2 + 1));
                }
            }
            
return bytes;
        }

        
/// <summary>
        
/// 高效的字符串转字节数组
        
/// </summary>
        
/// <param name="input"></param>
        
/// <returns></returns>
        public static byte[] StringToBytesH(string input)
        {
            
int len = input.Length;
            
if (len % 2 != 0)
            {
                
throw new Exception("输入的字符串长度有误,必须是偶数。");
            }
            
byte[] bytes = new byte[len / 2];
            
for (int i = 0; i < len / 2; i++)
            {
                
try
                {
                    bytes[i] 
= (byte)((CharToInt(input[2 * i]) << 4+ CharToInt(input[2 * i + 1]));
                }
                
catch (Exception e)
                {
                    
throw new Exception(string.Format("在位置{0}处的字符无法转换为16进制字节,原始信息为:{1}", i * 2 + 1, e.Message));
                }
            }
            
return bytes;
        }

        
/// <summary>
        
/// 使用指针效率最高
        
/// </summary>
        
/// <param name="input"></param>
        
/// <returns></returns>
        public static unsafe byte[] StringToBytesS(string input)
        {
            
int len = input.Length;
            
if (len % 2 != 0)
            {
                
throw new Exception("输入的字符串长度有误,必须是偶数。");
            }
            
byte[] bytes = new byte[len / 2];
            
fixed (byte* lbytes = bytes)
            {
                
fixed (char* linput = input)
                {
                    
byte* pbyte = lbytes;
                    
char* pchar = linput;
                    
for (int i = 0; i < len / 2; i++)
                    {
                        
try
                        {
                            
*pbyte = (byte)(CharToInt(*pchar) << 4);
                            pchar
++;
                            
*pbyte += (byte)CharToInt(*pchar);
                            pchar
++;
                            pbyte
++;
                        }
                        
catch (Exception e)
                        {
                            
throw new Exception(string.Format("在位置{0}处的字符无法转换为16进制字节,原始信息为:{1}", i * 2 + 1, e.Message));
                        }
                    }
                }
            }
            
return bytes;
        }
        
/// <summary>
        
/// 输入一个16进制字符,返回小于16的正整数
        
/// </summary>
        
/// <param name="input">16进制字符</param>
        
/// <returns>小于16的正整数</returns>
        private static int CharToInt(char input)
        {
            
if (input >= '0' && input <= '9')
            {
                
return input - '0';
            }
            
else if (input >= 'a' && input <= 'z')
            {
                
return input - 'a' + 10;
            }
            
else if (input >= 'A' && input <= 'Z')
            {
                
return input - 'A' + 10;
            }
            
throw new Exception(string.Format("字符({0})超出16进制范围,无法转换", input));
        }

        
/// <summary>
        
/// 输入一个小于16的正整数,返回对应的16进制字符。
        
/// </summary>
        
/// <param name="input">小于16的正整数</param>
        
/// <returns>16进制字符</returns>
        private static char IntToChar(int input)
        {
            
if (input >= 0 && input <= 9)
            {
                
return (char)(input + '0');
            }
            
else if (input >= 10 && input <= 15)
            {
                
return (char)(input - 10 + 'A');
            }
            
throw new Exception(string.Format("输入({0})超出16进制范围,无法转换", input));
        }
    }
posted @ 2011-04-18 15:31  leeolevis  阅读(894)  评论(0编辑  收藏  举报