byte流转字符串 字符串转byte流

    /// <summary>
    /// byte[]流转十六进制字符串 0x34---->"34"
    /// </summary>
    /// <param name="bytes"></param>
    /// <returns></returns>
    public static string ToHexString(byte[] bytes)
    {
        char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7','8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        char[] chars = new char[bytes.Length * 2];
        for (int i = 0; i < bytes.Length; i++)
        {
            int b = bytes[i];//十六进制转化为十进制 0x34->52
            chars[i * 2] = hexDigits[b >> 4];
            chars[i * 2 + 1] = hexDigits[b & 0xF];
        }
        return new string(chars);
    }

 

    /// <summary>
    ///  字符串转byte    "34"---->52 (0x34)
    /// </summary>
    /// <param name="strAsccii"></param>
    /// <returns></returns>
    public static byte ConvertAscciiToByte(string strAsccii)
    {
        strAsccii = strAsccii.Trim();
        if (strAsccii.Length > 2 || strAsccii.Length < 1) return 0x00;
        return byte.Parse(strAsccii, System.Globalization.NumberStyles.AllowHexSpecifier);
    }

测试代码:

    static void Main(string[] args)
    {
        Console.WriteLine("=========================");
        Console.WriteLine(" 源字符串为\"12345678\"");
        
        string nums = "12345678";
        byte[] bytes1=new byte[4];
        
        for (int n = 0; n < nums.Length/2; n++)
        {
            bytes1[n] = ConvertAscciiToByte(nums.Substring(n * 2, 2));
        }
        Console.WriteLine("12345678字符串转化为byte[]为 '" + bytes1[0].ToString("X") + " " + bytes1[1].ToString("X") + " "
            + bytes1[2].ToString("X") + " " + bytes1[3].ToString("X")+"'");

        string outStr = ToHexString(bytes1);
        Console.WriteLine("byte[]流转化为字符串为'"+outStr.ToString()+"'");

        Console.Read();
    }

输出结果:

posted @ 2012-07-18 21:10  泽刚  阅读(6777)  评论(0编辑  收藏  举报