2010年10月3日 星期日

【C#】String to Byte

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

沒有留言: