Skip to content

Instantly share code, notes, and snippets.

@gleox
Created March 13, 2019 03:30
Show Gist options
  • Save gleox/ac37bcc4d7186f0e40c8b07e94d682ab to your computer and use it in GitHub Desktop.
Save gleox/ac37bcc4d7186f0e40c8b07e94d682ab to your computer and use it in GitHub Desktop.
Helper to convert byte array(blob) to hex string.
using System;
namespace FipsTest
{
public static class Hex
{
public const string HexDigits = "0123456789abcdef";
private static char[] _lowerDigits;
private static char[] _upperDigits;
public static char[] LowerDigits => _lowerDigits ?? (_lowerDigits = GetHexDigits(true));
public static char[] UpperDigits => _upperDigits ?? (_upperDigits = GetHexDigits(false));
public static string ToHex(this byte[] data, bool toLowerCase = true) => ToHex(data, 0, data.Length, toLowerCase);
public static string ToHex(this byte[] data, int start, int length, bool toLowerCase = true)
{
// https://stackoverflow.com/questions/9655181/how-to-convert-a-byte-array-to-a-hex-string-in-java/9855338#9855338
// http://svn.apache.org/viewvc/commons/proper/codec/trunk/src/main/java/org/apache/commons/codec/binary/Hex.java?view=markup#l175
if (start < 0 || start >= data.Length && start > 0)
throw new ArgumentOutOfRangeException(nameof(start), "Value cannot be less that zero.");
if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length), "Value must be positive.");
if (start > data.Length - length)
throw new ArgumentException("Destination array is not long enough to copy all the items in the collection. Check array index and length.");
if (length == 0) return string.Empty;
if (length > (int.MaxValue / 2))
throw new ArgumentOutOfRangeException(nameof(length), $"The specified length exceeds the maximum value of {int.MaxValue / 2}.");
var size = length * 2;
var array = new char[size];
var digits = toLowerCase ? LowerDigits : UpperDigits;
for (int i = start, j = 0; j < size; i++)
{
array[j++] = digits[(0xF0 & data[i]) >> 4];
array[j++] = digits[0x0F & data[i]];
}
return new string(array, 0, size);
}
private static char[] GetHexDigits(bool toLowerCase)
{
var source = HexDigits;
return (toLowerCase ? source : source.ToUpperInvariant()).ToCharArray();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment