byte[]和16进制字符串的互相转换

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);
        }

总结,第三种效率最高

转载于:https://www.cnblogs.com/Pcant/archive/2008/10/24/1318486.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值