private static string FormatBigIntegerToHexString(BigInteger value, char format, int digits, NumberFormatInfo info)
{
StringBuilder sb = new StringBuilder();
byte[] bits = value.ToByteArray();
string fmt = null;
int cur = bits.Length - 1;
if (cur > -1)
{
// [FF..F8] drop the high F as the two's complement negative number remains clear
// [F7..08] retain the high bits as the two's complement number is wrong without it
// [07..00] drop the high 0 as the two's complement positive number remains clear
bool clearHighF = false;
byte head = bits[cur];
if (head > 0xF7)
{
head -= 0xF0;
clearHighF = true;
}
if (head < 0x08 || clearHighF)
{
// {0xF8-0xFF} print as {8-F}
// {0x00-0x07} print as {0-7}
fmt = string.Format(CultureInfo.InvariantCulture, "{0}1", format);
sb.Append(head.ToString(fmt, info));
cur--;
}
}
if (cur > -1)
{
fmt = string.Format(CultureInfo.InvariantCulture, "{0}2", format);
while (cur > -1)
{
sb.Append(bits[cur--].ToString(fmt, info));
}
}
if (digits > 0 && digits > sb.Length)
{
// Insert leading zeros. User specified "X5" so we create "0ABCD" instead of "ABCD"
sb.Insert(0, (value._sign >= 0 ? ("0") : (format == 'x' ? "f" : "F")), digits - sb.Length);
}
return sb.ToString();
}