Zi 字媒體
2017-07-25T20:27:27+00:00
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 );
寫了
5860316篇文章,獲得
23313次喜歡