C# 16進制字節轉Int(涉及:Base64轉byte數組)


十年河東,十年河西,莫欺少年窮

學無止境,精益求精

一個字節數組,如下:

 List<byte> by2 = new List<byte>() {0x55,0x22 };//8789

其對應的十進制的值為:8789

 從上圖可知,C#中byte數組默認為低字節在前

再例如:

List<byte> by3 = new List<byte>() { 0x55, 0x22 ,0x11};//1122901

對應的十進制是:1122901

對應的16進制為:0x112255,如下:

 經過上述兩個案例,C#byte數組中是按照低字節在前的方式排列的。

C#中有什么方法轉化字節流為Int嗎?

            List<byte> by2 = new List<byte>() {0x55,0x22 };//8789
            int ResultInt16 = BitConverter.ToInt16(by2.ToArray(), 0);
            List<byte> by4 = new List<byte>() { 0x55, 0x22, 0x11, 0x01 };//1428295937 
            int ResultInt32 = BitConverter.ToInt32(by4.ToArray(), 0);

涉及到兩個方法:BitConverter.ToInt16 和 BitConverter.ToInt32

但是::BitConverter.ToInt這個方法只能轉化長度為2或者長度為4的字節數組,如果字節長度為3,則無法轉化。

譬如:

 List<byte> by3 = new List<byte>() { 0x55, 0x22 ,0x11};//1122901

因此,有必要做一個通用方法

在實際業務需求中,軟硬件雙方制定的通訊協議中經常為字節流指定是高字節在前?還是低字節在前?

因此,我總結的方法如下:

#region C# 字節轉Int

        public static int GetValue(byte by)
        {
            return Convert.ToInt32(by);
        }

        #region 16進制轉十進制 高字節在前
        /// <summary>
        /// 16進制轉十進制 高字節在前
        /// </summary>
        /// <param name="Ary"></param>
        /// <returns></returns>
        public static int GetValue(List<byte> Ary)
        {
            double result = 0;
            var cm = 0;
            cm = Ary.Count;
            foreach (var item in Ary)
            {
                if (cm - 1 == 0)
                {
                    result += item;
                }
                else
                {
                    result += item * Math.Pow(16, (cm * 2 - 2));
                    cm--;
                }

            }
            return Convert.ToInt32(result);
        }
        /// <summary>
        /// 高字節在前
        /// </summary>
        /// <param name="Ary"></param>
        /// <returns></returns>
        public static int GetValue(IEnumerable<byte> Ary)
        {
            double result = 0;
            var cm = 0;
            cm = Ary.Count();
            foreach (var item in Ary)
            {
                if (cm - 1 == 0)
                {
                    result += item;
                }
                else
                {
                    result += item * Math.Pow(16, (cm * 2 - 2));
                    cm--;
                }

            }
            return Convert.ToInt32(result);
        }
        /// <summary>
        /// 16進制轉十進制 具體參考十六進制的數值
        /// </summary>
        /// <param name="Ary"></param>
        /// <returns></returns>
        public static int GetValue(List<int> Ary)
        {
            double result = 0;
            var cm = 0;
            cm = Ary.Count;
            foreach (var item in Ary)
            {
                if (cm - 1 == 0)
                {
                    result += item;
                }
                else
                {
                    result += item * Math.Pow(16, (cm * 2 - 2));
                    cm--;
                }

            }
            return Convert.ToInt32(result);
        }
        /// <summary>
        /// 16進制轉十進制
        /// </summary>
        /// <param name="Ary"></param>
        /// <returns></returns>
        public static int GetValue(IEnumerable<int> Ary)
        {
            double result = 0;
            var cm = 0;
            cm = Ary.Count();
            foreach (var item in Ary)
            {
                if (cm - 1 == 0)
                {
                    result += item;
                }
                else
                {
                    result += item * Math.Pow(16, (cm * 2 - 2));
                    cm--;
                }

            }
            return Convert.ToInt32(result);
        }
        #endregion

        #region 16進制轉十進制 低字節在前
        /// <summary>
        /// 16進制轉十進制 高字節在前
        /// </summary>
        /// <param name="Ary"></param>
        /// <returns></returns>
        public static int GetValueLH(List<byte> Ary)
        {
            Ary.Reverse();
            double result = 0;
            var cm = 0;
            cm = Ary.Count;
            foreach (var item in Ary)
            {
                if (cm - 1 == 0)
                {
                    result += item;
                }
                else
                {
                    result += item * Math.Pow(16, (cm * 2 - 2));
                    cm--;
                }

            }
            return Convert.ToInt32(result);
        }
        /// <summary>
        /// 低字節在前
        /// </summary>
        /// <param name="Ary"></param>
        /// <returns></returns>
        public static int GetValueLH(IEnumerable<byte> Ary)
        {
            Ary.Reverse();
            double result = 0;
            var cm = 0;
            cm = Ary.Count();
            foreach (var item in Ary)
            {
                if (cm - 1 == 0)
                {
                    result += item;
                }
                else
                {
                    result += item * Math.Pow(16, (cm * 2 - 2));
                    cm--;
                }

            }
            return Convert.ToInt32(result);
        }
        /// <summary>
        /// 16進制轉十進制 低字節在前
        /// </summary>
        /// <param name="Ary"></param>
        /// <returns></returns>
        public static int GetValueLH(List<int> Ary)
        {
            Ary.Reverse();
            double result = 0;
            var cm = 0;
            cm = Ary.Count;
            foreach (var item in Ary)
            {
                if (cm - 1 == 0)
                {
                    result += item;
                }
                else
                {
                    result += item * Math.Pow(16, (cm * 2 - 2));
                    cm--;
                }

            }
            return Convert.ToInt32(result);
        }
        /// <summary>
        /// 16進制轉十進制 低字節在前
        /// </summary>
        /// <param name="Ary"></param>
        /// <returns></returns>
        public static int GetValueLH(IEnumerable<int> Ary)
        {
            Ary.Reverse();
            double result = 0;
            var cm = 0;
            cm = Ary.Count();
            foreach (var item in Ary)
            {
                if (cm - 1 == 0)
                {
                    result += item;
                }
                else
                {
                    result += item * Math.Pow(16, (cm * 2 - 2));
                    cm--;
                }

            }
            return Convert.ToInt32(result);
        }
        #endregion

        #endregion

 

擴展:int數值轉字節:

 

var by4 = BitConverter.GetBytes(8888);//長度四字節
var by2 = BitConverter.GetBytes(Convert.ToUInt16(8888));//長度兩字節

C# base64 轉 byte[]

        static void Main(string[] args)
        {
            string btinfo = @"MDAwMDAwMDAwMDAwMDAwMAHgAMgB7wAATjcBAXEBqAADAGEM7QzoR0UPDOkM6wzrDOkM6QzsDOwM7QzrDOgM6gzpDOoM6QzpAkdFAAAAAAANAQEBAQEBAAAAAAAAAAAAAAA=";
            var Bys = Encoding.Default.GetBytes(btinfo);
            var Bse64Bys = Convert.FromBase64String(btinfo);
            Console.WriteLine("普通byte數組,8位表示一個普通字符,長度為:"+Bys.Length);
            Console.WriteLine("Base64byte數組,6位表示一個base64字符,長度為:" + Bse64Bys.Length);
            Console.ReadLine();
        }

繼續轉發別人的一篇【2020-12-24】

C#中的Byte,String,Int,Hex之間的轉換函數

 轉化字符串:aabb00000000001a160100000008313233343536373839303131323233330100ffff9775 為字節數組

整理轉換方法:

復制代碼
 public class BytesTranfer
    {
        /// <summary> Convert a string of hex digits (ex: E4 CA B2) to a byte array. </summary>
        /// <param name="s"> The string containing the hex digits (with or without spaces). </param>
        /// <returns> Returns an array of bytes. </returns>
        public byte[] HexStringToByteArray(string s)
        {
            s = s.Replace(" ", "");
            byte[] buffer = new byte[s.Length / 2];
            for (int i = 0; i < s.Length; i += 2)
            {
                buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);
            }

            return buffer;
        }

        /// <summary> Converts an array of bytes into a formatted string of hex digits (ex: E4 CA B2)</summary>
        /// <param name="data"> The array of bytes to be translated into a string of hex digits. </param>
        /// <returns> Returns a well formatted string of hex digits with spacing. </returns>
        public string ByteArrayToHexString(byte[] data)
        {
            StringBuilder sb = new StringBuilder(data.Length * 3);
            foreach (byte b in data)
            {
                sb.Append(Convert.ToString(b, 16).PadLeft(2, '0').PadRight(3, ' '));
            }

            return sb.ToString().ToUpper();
        }

        /// <summary>
        /// 將一條十六進制字符串轉換為ASCII
        /// </summary>
        /// <param name="hexstring">一條十六進制字符串</param>
        /// <returns>返回一條ASCII碼</returns>
        public static string HexStringToASCII(string hexstring)
        {
            byte[] bt = HexStringToBinary(hexstring);
            string lin = "";
            for (int i = 0; i < bt.Length; i++)
            {
                lin = lin + bt[i] + " ";
            }


            string[] ss = lin.Trim().Split(new char[] { ' ' });
            char[] c = new char[ss.Length];
            int a;
            for (int i = 0; i < c.Length; i++)
            {
                a = Convert.ToInt32(ss[i]);
                c[i] = Convert.ToChar(a);
            }

            string b = new string(c);
            return b;
        }


        /**/
        /// <summary>
        /// 16進制字符串轉換為二進制數組
        /// </summary>
        /// <param name="hexstring">用空格切割字符串</param>
        /// <returns>返回一個二進制字符串</returns>
        public static byte[] HexStringToBinary(string hexstring)
        {

            string[] tmpary = hexstring.Trim().Split(' ');
            byte[] buff = new byte[tmpary.Length];
            for (int i = 0; i < buff.Length; i++)
            {
                buff[i] = Convert.ToByte(tmpary[i], 16);
            }
            return buff;
        }


        /// <summary>
        /// 將byte型轉換為字符串
        /// </summary>
        /// <param name="arrInput">byte型數組</param>
        /// <returns>目標字符串</returns>
        private string ByteArrayToString(byte[] arrInput)
        {
            int i;
            StringBuilder sOutput = new StringBuilder(arrInput.Length);
            for (i = 0; i < arrInput.Length; i++)
            {
                sOutput.Append(arrInput[i].ToString("X2"));
            }
            //將此實例的值轉換為System.String
            return sOutput.ToString();
        }



        /// <summary>
        /// 對接收到的數據進行解包(將接收到的byte型數組解包為Unicode字符串)
        /// </summary>
        /// <param name="recbytes">byte型數組</param>
        /// <returns>Unicode編碼的字符串</returns>
        public string disPackage(byte[] recbytes)
        {
            string temp = "";
            foreach (byte b in recbytes)
                temp += b.ToString("X2") + " ";//ToString("X2") 為C#中的字符串格式控制符
            return temp;
        }

        /**
    * int轉byte[]
    * 該方法將一個int類型的數據轉換為byte[]形式,因為int為32bit,而byte為8bit所以在進行類型轉換時,知會獲取低8位,
    * 丟棄高24位。通過位移的方式,將32bit的數據轉換成4個8bit的數據。注意 &0xff,在這當中,&0xff簡單理解為一把剪刀,
    * 將想要獲取的8位數據截取出來。
    * @param i 一個int數字
    * @return byte[]
    */
        public static byte[] int2ByteArray(int i)
        {
            byte[] result = new byte[4];
            result[0] = (byte)((i >> 24) & 0xFF);
            result[1] = (byte)((i >> 16) & 0xFF);
            result[2] = (byte)((i >> 8) & 0xFF);
            result[3] = (byte)(i & 0xFF);
            return result;
        }
        /**
         * byte[]轉int
         * 利用int2ByteArray方法,將一個int轉為byte[],但在解析時,需要將數據還原。同樣使用移位的方式,將適當的位數進行還原,
         * 0xFF為16進制的數據,所以在其后每加上一位,就相當於二進制加上4位。同時,使用|=號拼接數據,將其還原成最終的int數據
         * @param bytes byte類型數組
         * @return int數字
         */
        public static int bytes2Int(byte[] bytes)
        {
            int num = bytes[3] & 0xFF;
            num |= ((bytes[2] << 8) & 0xFF00);
            num |= ((bytes[1] << 16) & 0xFF0000);
            num |= ((bytes[0] << 24) & 0xFF0000);
            return num;
        }

        public static string Int2String(int str)
        {
            string S = Convert.ToString(str);
            return S;
        }

        public static int String2Int(string str)
        {
            int a;
            int.TryParse(str, out a);
            int a1 = Convert.ToInt32(str);
            return a1;
        }


        /*將int轉為低字節在后,高字節在前的byte數組
b[0] = 11111111(0xff) & 01100001
b[1] = 11111111(0xff) & 00000000
b[2] = 11111111(0xff) & 00000000
b[3] = 11111111(0xff) & 00000000
*/
        public byte[] IntToByteArray2(int value)
        {
            byte[] src = new byte[4];
            src[0] = (byte)((value >> 24) & 0xFF);
            src[1] = (byte)((value >> 16) & 0xFF);
            src[2] = (byte)((value >> 8) & 0xFF);
            src[3] = (byte)(value & 0xFF);
            return src;
        }
        //將高字節在前轉為int,低字節在后的byte數組(與IntToByteArray2想對應)
        public int ByteArrayToInt2(byte[] bArr)
        {
            if (bArr.Length != 4)
            {
                return -1;
            }
            return (int)((((bArr[0] & 0xff) << 24)
                       | ((bArr[1] & 0xff) << 16)
                       | ((bArr[2] & 0xff) << 8)
   | ((bArr[3] & 0xff) << 0)));
        }

        public static string StringToHexArray(string input)
        {
            char[] values = input.ToCharArray();
            StringBuilder sb = new StringBuilder(input.Length * 3);
            foreach (char letter in values)
            {
                // Get the integral value of the character.
                int value = Convert.ToInt32(letter);
                // Convert the decimal value to a hexadecimal value in string form.
                string hexOutput = String.Format("{0:X}", value);
                sb.Append(Convert.ToString(value, 16).PadLeft(2, '0').PadRight(3, ' '));
            }

            return sb.ToString().ToUpper();



        }
    }
復制代碼

附上查找資料過程中有用的一些資料地址:

https://www.cnblogs.com/ThreeS/articles/9377547.html

https://www.cnblogs.com/screes/p/5633383.html

還有一個關於補零的:https://blog.csdn.net/qq_22889875/article/details/79320678

 

@天才卧龍的博客


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM