Last active
December 16, 2015 05:59
-
-
Save smonn/5388457 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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