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

输出结果:

转载于:https://www.cnblogs.com/kingkongv/archive/2012/07/18/2598140.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值