2017年8月6日 星期日

C# byte[] 轉 Hex String 與 Hex String 轉 byte[]

 C# byte[] 轉 Hex String 與 Hex String 轉 byte[]

/// <summary>
/// byte[] 轉 Hex String
/// </summary>
/// <param name="bytes">byte[]</param>
/// <returns>Hex String</returns>
protected 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;
}

========================================

/// <summary>
/// Hex String 轉 byte[]
/// </summary>
/// <param name="newString">Hex String</param>
/// <returns>byte[]</returns>
protected 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;
}

private 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;
}

Reference Web:
<a href="http://blog.xuite.net/jen999999/blog/124905329-C%23+byte%5B%5D%E8%BD%89%E6%88%90string+%E8%88%87+string%E8%BD%89%E6%88%90byte%5B%5D"></a>