search
尋找貓咪~QQ 地點 桃園市桃園區 Taoyuan , Taoyuan

C# 字串轉BYTE陣列 、 BYTE陣列轉字串 和 BYTE陣列轉16進為字串 – jashliao部落格

C# 字串轉BYTE陣列 、 BYTE陣列轉字串 和 BYTE陣列轉16進為字串


 

 

BYTE陣列轉16進為字串

 public static bool ByteArray2String(byte[] pdata, ref String StrData, bool blnReverse = true)//陣列轉字串
        {
            StrData = "";
            bool blnResult = true;

            if (blnReverse == true)
            {
                Array.Reverse(pdata);
            }

            try
            {
                for (int i = 0; i < pdata.Length; i++)
                {
                    StrData += Convert.ToString(pdata[i], 16).PadLeft(2, '0') + " ";
                }
            }
            catch
            {
                blnResult = false;
            }
            return blnResult;
        } 


 16進為字串BYTE陣列

        public static bool String2ByteArray(byte[] pkey, String StrData, int iLen = 16)
        {
            bool blnResult = true;
            if (StrData.Length >= (iLen * 2))
            {
                int j = 0;
                //for (int i = 0; i < StrData.Length; i += 2)
                for (int i = (StrData.Length - 2); i >= 0; i -= 2)
                {
                    try
                    {

                        int buf = Convert.ToInt32(StrData.Substring(i, 2), 16);
                        pkey[j] = Convert.ToByte(buf);
                        j++;
                    }
                    catch
                    {
                        blnResult = false;
                        break;
                    }
                }
            }
            return blnResult;
        }

string類型轉成byte[]:

byte[] byteArray = System.Text.Encoding.Default.GetBytes ( str );

反過來,byte[]轉成string:

string str = System.Text.Encoding.Default.GetString ( byteArray );

string類型轉成ASCII byte[]:(”01″ 轉成 byte[] = new byte[]{ 0x30, 0x31})

byte[] byteArray = System.Text.Encoding.ASCII.GetBytes ( str );

ASCII byte[] 轉成string:(byte[] = new byte[]{ 0x30, 0x31} 轉成 “01”)

string str = System.Text.Encoding.ASCII.GetString ( byteArray );



熱門推薦

本文由 jashliaoeuwordpress 提供 原文連結

寵物協尋 相信 終究能找到回家的路
寫了7763篇文章,獲得2次喜歡
留言回覆
回覆
精彩推薦