2018年11月7日 星期三

【C#】0x string to byte[] and convert back

MD5 測試用到的

public static byte[] HexStrToByteArray(string hex)
{
    int NumberChars = hex.Length;
    byte[] bytes = new byte[NumberChars / 2];
    for (int i = 0; i < NumberChars; i += 2)
        bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
    return bytes;
}

public static string ByteArrayToHexStr(byte[] data)
{
    if (data == null)
        return string.Empty;
    if (data.Length == 0)
        return string.Empty;
    StringBuilder dataStr = new StringBuilder();

    dataStr.Append("0x");
    foreach (byte b in data)
        dataStr.Append(b.ToString("X2"));
    return dataStr.ToString();
}
ref: to byte array,   to hex string,   binary to hex string in TSQL

沒有留言:

張貼留言