兔八哥极品软件园    运行: 4497天 | 文章:640 篇 | 评论:505 条 | 碎语:1条

c# 字节数组,十六进制相互转换byte[],hex

作者:admin 发布于:2014-3-7 16:22 Friday 分类:.NET


/// <summary> 
/// 字符串转16进制字节数组 
/// </summary> 
/// <param name="hexString"></param> 
/// <returns></returns> 
private static byte[] strToToHexByte(string hexString) 
{ 
hexString = hexString.Replace(" ", ""); 
if ((hexString.Length % 2) != 0) 
hexString += " "; 
byte[] returnBytes = new byte[hexString.Length / 2]; 
for (int i = 0; i < returnBytes.Length; i++) 
returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16); 
return returnBytes; 
} 
字节数组转16进制字符串 
/// <summary> 
/// 字节数组转16进制字符串 
/// </summary> 
/// <param name="bytes"></param> 
/// <returns></returns> 
public static string byteToHexStr(byte[] bytes) 
{ 
string returnStr = ""; 
if (bytes != null) 
{ 
for (int i = 0; i < bytes.Length; i++) 
{ 
returnStr += bytes[i].ToString("X2"); 
} 
} 
return returnStr; 
} 
从汉字转换到16进制 
/// <summary> 
/// 从汉字转换到16进制 
/// </summary> 
/// <param name="s"></param> 
/// <param name="charset">编码,如"utf-8","gb2312"</param> 
/// <param name="fenge">是否每字符用逗号分隔</param> 
/// <returns></returns> 
public static string ToHex(string s, string charset, bool fenge) 
{ 
if ((s.Length % 2) != 0) 
{ 
s += " ";//空格 
//throw new ArgumentException("s is not valid chinese string!"); 
} 
System.Text.Encoding chs = System.Text.Encoding.GetEncoding(charset); 
byte[] bytes = chs.GetBytes(s); 
string str = ""; 
for (int i = 0; i < bytes.Length; i++) 
{ 
str += string.Format("{0:X}", bytes[i]); 
if (fenge && (i != bytes.Length - 1)) 
{ 
str += string.Format("{0}", ","); 
} 
} 
return str.ToLower(); 
} 
16进制转换成汉字 
///<summary> 
/// 从16进制转换成汉字 
/// </summary> 
/// <param name="hex"></param> 
/// <param name="charset">编码,如"utf-8","gb2312"</param> 
/// <returns></returns> 
public static string UnHex(string hex, string charset) 
{ 
if (hex == null) 
throw new ArgumentNullException("hex"); 
hex = hex.Replace(",", ""); 
hex = hex.Replace("\n", ""); 
hex = hex.Replace("\\", ""); 
hex = hex.Replace(" ", ""); 
if (hex.Length % 2 != 0) 
{ 
hex += "20";//空格 
} 
// 需要将 hex 转换成 byte 数组。 
byte[] bytes = new byte[hex.Length / 2]; 
for (int i = 0; i < bytes.Length; i++) 
{ 
try 
{ 
// 每两个字符是一个 byte。 
bytes[i] = byte.Parse(hex.Substring(i * 2, 2), 
System.Globalization.NumberStyles.HexNumber); 
} 
catch 
{ 
// Rethrow an exception with custom message. 
throw new ArgumentException("hex is not a valid hex number!", "hex"); 
} 
} 
System.Text.Encoding chs = System.Text.Encoding.GetEncoding(charset); 
return chs.GetString(bytes); 
} 

/////////////////////////////////////////////////////
public class CommonUtil {
    /** 
     * byte数组转换成16进制字符串 
     * @param src 
     * @return 
     */  
    public static String bytesToHexString(byte[] src){       
           StringBuilder stringBuilder = new StringBuilder();       
           if (src == null || src.length <= 0) {       
               return null;       
           }       
           for (int i = 0; i < src.length; i++) {       
               int v = src[i] & 0xFF;       
               String hv = Integer.toHexString(v);       
               if (hv.length() < 2) {       
                   stringBuilder.append(0);       
               }       
               stringBuilder.append(hv);       
           }       
           return stringBuilder.toString();       
       }
    
    /** 
     * byte数组转换成16进制字符数组
     * @param src 
     * @return 
     */  
    public static String[] bytesToHexStrings(byte[] src){       
           if (src == null || src.length <= 0) {       
               return null;       
           }
           String[] str = new String[src.length];
           
           for (int i = 0; i < src.length; i++) {       
               int v = src[i] & 0xFF;       
               String hv = Integer.toHexString(v);       
               if (hv.length() < 2) {       
                   str[i] = "0";       
               }       
               str[i] = hv;        
           }       
           return str;       
       }

}
////////////////////////////////////////////////////
namespace Jerry.Framework.Socket.Common
{
    public class Utility
    {
        /// <summary>
        /// 将指定进制的字符串转换到指定进制的字符串
        /// </summary>
        /// <param name="value">要转换的字符串</param>
        /// <param name="fromBase">value 中数字的基数,它必须是 2、8、10 或 16。</param>
        /// <param name="toBase">value 中数字的基数,它必须是 2、8、10 或 16。</param>
        /// <returns></returns>
        public static string ToString(string value, int fromBase, int toBase)
        {
            return Convert.ToString(Convert.ToInt32(value, fromBase), toBase);
        }

        /// <summary>
        /// 将字节数组节转换成指定进制的字符串
        /// </summary>
        /// <param name="byteArray">要转换的字符串</param>
        /// <param name="toBase">它必须是 2 或 16</param>
        /// <returns></returns>
        public static string ToString(byte[] byteArray, int toBase = 16)
        {
            if (byteArray == null || byteArray.Length == 0)
                return string.Empty;

            switch (toBase)
            {
                case 2:
                    return ByteArrayToBinaryString(byteArray);
                case 16:
                    return ByteArrayToHexStr(byteArray);
                default:
                    return string.Empty;
            }
        }

        /// <summary>
        /// 将指定进制的字符串转换成字节数组
        /// </summary>
        /// <param name="value"></param>
        /// <param name="fromBase"></param>
        /// <returns></returns>
        public static byte[] ToByteArray(string value, int fromBase = 16)
        {
            if (string.IsNullOrEmpty(value))
                return null;
            switch (fromBase)
            {
                case 2:
                    return BinaryStringToByteArray(value);
                case 16:
                    return HexStrToByteArray(value);
                default:
                    return null;
            }
        }

        /// <summary>
        /// 字节数组节转换成二进制字符串
        /// </summary>
        /// <param name="b">要转换的字节数组</param>
        /// <returns></returns>
        private static string ByteArrayToBinaryString(byte[] byteArray)
        {
            int capacity = byteArray.Length * 8;
            StringBuilder sb = new StringBuilder(capacity);
            for (int i = 0; i < byteArray.Length; i++)
            {
                sb.Append(byte2BinString(byteArray[i]));
            }
            return sb.ToString();
        }

        private static string byte2BinString(byte b)
        {
            return Convert.ToString(b, 2).PadLeft(8, '0');
        }

        /// <summary>
        /// 二进制字符串转换成字节数组
        /// </summary>
        /// <param name="binaryString">要转换的字符,如"00000000 11111111"</param>
        /// <returns></returns>
        private static byte[] BinaryStringToByteArray(string binaryString)
        {
            binaryString = binaryString.Replace(" ", "");

            if ((binaryString.Length % 8) != 0)
                throw new ArgumentException("二进制字符串长度不对");

            byte[] buffer = new byte[binaryString.Length / 8];
            for (int i = 0; i < buffer.Length; i++)
            {
                buffer[i] = Convert.ToByte(binaryString.Substring(i * 8, 8).Trim(), 2);
            }
            return buffer;

        }

        /// <summary>
        /// 字节数组转换成十六进制字符串
        /// </summary>
        /// <param name="bytes">要转换的字节数组</param>
        /// <returns></returns>
        private static string ByteArrayToHexStr(byte[] byteArray)
        {
            int capacity = byteArray.Length * 2;
            StringBuilder sb = new StringBuilder(capacity);

            if (byteArray != null)
            {
                for (int i = 0; i < byteArray.Length; i++)
                {
                    sb.Append(byteArray[i].ToString("X2"));
                }
            }
            return sb.ToString();
        }

        /// <summary>
        /// 十六进制字符串转换成字节数组 
        /// </summary>
        /// <param name="hexString">要转换的字符串</param>
        /// <returns></returns>
        private static byte[] HexStrToByteArray(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
                throw new ArgumentException("十六进制字符串长度不对");
            byte[] buffer = new byte[hexString.Length / 2];
            for (int i = 0; i < buffer.Length; i++)
            {
                buffer[i] = Convert.ToByte(hexString.Substring(i * 2, 2).Trim(), 0x10);
            }
            return buffer;
        }
    }
}

标签: byte[]


Powered by 兔八哥极品软件 苏ICP备12049267号 sitemap