Zi 字媒體
2017-07-25T20:27:27+00:00
C# string和byte[]的轉換
資料來源:http://isanhsu.blogspot.tw/2012/03/stringbyte-c.html
01.string類型轉成byte[]:
byte[] byteArray = System.Text.Encoding.Default.GetBytes ( str );
02.byte[]轉成string:
string str = System.Text.Encoding.Default.GetString ( byteArray );
03.16進制陣列轉字串
public static string ToHexString(byte[] bytes)
{
string hexString = string.Empty;
if (bytes != null)
{
StringBuilder str = new StringBuilder();
for (int i = 0; i < bytes.Length; i++)
{
str.Append(bytes[i].ToString(“X2”));
}
hexString = str.ToString();
}
return hexString;
}
03.字串轉16進制陣列
public static byte[] GetBytes(string HexString)
{
int byteLength = HexString.Length / 2;
byte[] bytes = new byte[byteLength];
string hex;
int j = 0;
for (int i = 0; i < bytes.Length; i++)
{
hex = new String(new Char[] { HexString[j], HexString[j + 1] });
bytes[i] = HexToByte(hex);
j = j + 2;
}
return bytes;
}
public static byte HexToByte(string hex)
{
if (hex.Length > 2 || hex.Length <= 0)
throw new ArgumentException(“hex must be 1 or 2 characters in length”);
byte newByte = byte.Parse(hex, System.Globalization.NumberStyles.HexNumber);
return newByte;
}
寫了
5860316篇文章,獲得
23313次喜歡