Skip to content

Instantly share code, notes, and snippets.

@smonn
Last active December 16, 2015 05:59
Show Gist options
  • Save smonn/5388457 to your computer and use it in GitHub Desktop.
Save smonn/5388457 to your computer and use it in GitHub Desktop.
using System;
using System.Linq;
namespace SystemExtensions
{
public static class HexadecimalExtensions
{
/// <summary>
/// Converts a byte array to a hexadecimal string.
/// </summary>
/// <param name="bytes">The byte array to convert.</param>
/// <returns>A hexadecimal string.</returns>
public static string ToHexadecimalString(this byte[] bytes)
{
return new string(bytes.SelectMany(x => x.ToString("x2").ToCharArray()).ToArray());
}
/// <summary>
/// Converts a hexadecimal string to a byte array.
/// </summary>
/// <param name="hex">The hexadecimal string to convert.</param>
/// <returns>A byte array.</returns>
public static byte[] ToByteArray(this string hex)
{
return Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment