hex string to byte[]
   public static byte[] StringToByte1(string value)
        {
            int len = value.Length / 2;
            byte[] ret = new byte[len];
            for (int i = 0; i < len; i++)
                ret[i] = (byte)Convert.ToInt32(value.Substring(i * 2, 2), 16);
            return ret;

        }

byte[] to hex string
1、BitConverter.ToString(bytes),然后把"-"replace掉
2、  public static string ConvertBytesToHex(byte[] value)
        {
            int num = value.Length;
            char[] chArray = new char[num * 2];
            int num2 = 0;
            for (int index = 0; index < (num * 2); index += 2)
            {
                byte num5 = value[num2++];
                chArray[index] = GetHexValue(num5 / 0x10);
                chArray[index + 1] = GetHexValue(num5 % 0x10);
            }
            return new string(chArray);
        }
        private static char GetHexValue(int i)
        {
            if (i < 10)
            {
                return (char)(i + 0x30);
            }
            return (char)((i - 10) + 0x41);
        }

3、   private static char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
        internal static string ToHexString(byte[] bytes)
        {
            int num = bytes.Length;
            char[] chars = new char[num * 2];
            for (int i = 0; i < num; i++)
            {
                int b = bytes[i];
                chars[i * 2] = hexDigits[b >> 4];
                chars[i * 2 + 1] = hexDigits[b & 0xF];
            }
            return new string(chars);
        }

总结,第三种效率最高

posted on 2008-10-24 09:49  绿蚂蚁  阅读(1907)  评论(3编辑  收藏  举报