C#之基础数据类型和字节数组的转换

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

/*
    将一个数字转换为Byte数组,让后将Byte数组转换为32为的整形数字
*/

namespace ByteDemo
{
    class Program
    {
        /// <summary>
        /// 将int转换为字节数组
        /// </summary>
        /// <param name="number"></param>
        /// <returns></returns>
        public byte[] IntConvertToByetArry(int number)
        {
            //BitConverter:将基础数据类型与字节数组相互转化
            byte[] bs = System.BitConverter.GetBytes(number);
            return bs;
        }

        /// <summary>
        /// 将bytes数组转换为int
        /// </summary>
        /// <param name="bs"></param>
        /// <returns></returns>
        public int ByteConvertToInt(byte[] bs)
        {
            int number = System.BitConverter.ToInt32(bs, 0);
            return number;
        }




        void PrintByetArry(byte[] bs)
        {
            Console.Write(" ConvertToByetArry is: ");
            foreach (var sBs in bs)
            {
                Console.Write(sBs+" ");
            }
            Console.WriteLine();
        }

        static void Main(string[] args)
        {
            Program pro = new Program();
            byte[] bs = pro.IntConvertToByetArry(20);
            pro.PrintByetArry(bs);
            Console.WriteLine(" ByteConvertToInt IntConvertToByetArry is " + pro.ByteConvertToInt(bs));
            Console.ReadKey();
        }
    }
}

你可能感兴趣的:(类型转换,C#,BitConverter)