16进制字符串和Byte之间的互转

public static class ByteHexHelper
{
    private static char[] _buffedChars = null;
    private static byte[] _buffedBytes = null;

    static ByteHexHelper()
    {
        _buffedChars = new char[(byte.MaxValue - byte.MinValue + 1) * 2];
        int idx = 0;
        byte b = byte.MinValue;
        while (true)
        {
            string hexs = b.ToString("X2");
            _buffedChars[idx++] = hexs[0];
            _buffedChars[idx++] = hexs[1];

            if (b == byte.MaxValue) break;
            ++b;
        }

        _buffedBytes = new byte[0x67];
        idx = _buffedBytes.Length;
        while (--idx >= 0)
        {
            if ((0x30 <= idx) && (idx <= 0x39))
            {
                _buffedBytes[idx] = (byte)(idx - 0x30);
            }
            else
            {
                if ((0x61 <= idx) && (idx <= 0x66))
                {
                    _buffedBytes[idx] = (byte)((idx - 0x61) + 10);
                    continue;
                }
                if ((0x41 <= idx) && (idx <= 70))
                {
                    _buffedBytes[idx] = (byte)((idx - 0x41) + 10);
                }
            }
        }
    }

    /// <summary>
    /// 字节数组转16进制字符串
    /// </summary>
    /// <param name="bytes"></param>
    /// <returns></returns>
    public static string ByteToHex(byte[] bytes)
    {
        if (bytes == null)
        {
            return null;
        }

        char[] result = new char[bytes.Length * 2];
        for (int i = 0; i < bytes.Length; ++i)
        {
            int startIndex = (bytes[i] - byte.MinValue) * 2;
            result[i * 2] = _buffedChars[startIndex];
            result[i * 2 + 1] = _buffedChars[startIndex + 1];
        }

        return new string(result);
    }

    /// <summary>
    /// 16进制字符串转字节数组
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static byte[] HexToByte(string str)
    {
        if (str == null || (str.Length & 1) == 1)
        {
            return null;
        }

        byte[] result = new byte[str.Length / 2];
        int charIndex = 0;
        int byteIndex = 0;
        int length = result.Length;
        while (--length >= 0)
        {
            int first = 0;
            int second = 0;
            try
            {
                first = _buffedBytes[str[charIndex++]];
                second = _buffedBytes[str[charIndex++]];
            }
            catch
            {
                return null;
            }
            result[byteIndex++] = (byte)((first << 4) + second);
        }
        return result;
    }
}

  

转载于:https://www.cnblogs.com/ahui/archive/2011/08/29/2157198.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值