Code: C# 中 string 以及 byte[] 之間互相轉換

今天寫程式遇到要 return byte[] 的情況
但是 C# 只能回傳整數或是字串
於是找了這個方法把 byte[] 的 Hex 轉成字串
之後再轉回 byte[]

//byte[] 轉字串
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; }

//字串轉 byte[] public static byte[] GetBytes(string newString, int discarded)
{
discarded = 0;

int byteLength = newString.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[] { newString[j], newString[j + 1] }); bytes[i] = HexToByte(hex); j = j + 2; } return bytes; } private 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; }

發表迴響

你的電子郵件位址並不會被公開。