// Converts an array of bytes into a String.
public static string ToString(byte[] value, int startIndex, int length)
{
if (value == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
}
if (startIndex < 0 || startIndex >= value.Length && startIndex > 0)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
}
if (length < 0)
{
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_GenericPositive);
}
if (startIndex > value.Length - length)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall, ExceptionArgument.value);
}
if (length == 0)
{
return(string.Empty);
}
if (length > (int.MaxValue / 3))
{
// (Int32.MaxValue / 3) == 715,827,882 Bytes == 699 MB
throw new ArgumentOutOfRangeException(nameof(length), SR.Format(SR.ArgumentOutOfRange_LengthTooLarge, (int.MaxValue / 3)));
}
#if __MonoCS__ //use old impl for mcs
const string HexValues = "0123456789ABCDEF";
int chArrayLength = length * 3;
char[] chArray = new char[chArrayLength];
int i = 0;
int index = startIndex;
for (i = 0; i < chArrayLength; i += 3)
{
byte b = value[index++];
chArray[i] = HexValues[b >> 4];
chArray[i + 1] = HexValues[b & 0xF];
chArray[i + 2] = '-';
}
return(new String(chArray, 0, chArray.Length - 1));
#else
return(string.Create(length * 3 - 1, (value, startIndex, length), (dst, state) =>
{
const string HexValues = "0123456789ABCDEF";
var src = new ReadOnlySpan <byte>(state.value, state.startIndex, state.length);
int i = 0;
int j = 0;
byte b = src[i++];
dst[j++] = HexValues[b >> 4];
dst[j++] = HexValues[b & 0xF];
while (i < src.Length)
{
b = src[i++];
dst[j++] = '-';
dst[j++] = HexValues[b >> 4];
dst[j++] = HexValues[b & 0xF];
}
}));
#endif
}