Microsoft .NET/C#

[C#] 16진수(hex) 문자열<-> Byte[] 변환

전자기린 2020. 1. 3. 20:02

1. 16진수 문자열 -> Byte[]

/// <summary>
/// 16진수 문자를 16진수 Byte[]로 변환
/// </summary>
/// <param name="strHex"></param>
/// <returns></returns>
/// 
public byte[] HexStringToByteHex(string strHex)
{
    if (strHex.Length % 2 != 0)
        MessageBox.Show("HexString는 홀수일 수 없습니다. - " + strHex);

    byte[] bytes = new byte[strHex.Length / 2];

    for (int count = 0; count < strHex.Length; count += 2)
    {
        bytes[count / 2] = System.Convert.ToByte(strHex.Substring(count, 2), 16);
    }
    return bytes;
}

 

2. Byte[] -> 16진수 문자열 

/// <summary>
/// 16진수 Byte[]를 16진수 문자로 변환
/// </summary>
/// <param name="strHex"></param>
/// <returns></returns>
/// 
public string ByteHexToHexString(byte[] hex)
{
    string result = string.Empty;
    foreach (byte c in hex)
        result += c.ToString("x2").ToUpper();
    return result;
}