Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
Expand Down Expand Up @@ -827,14 +828,40 @@ static void ThrowInvalid(NumberStyles value)

internal static void ValidateParseStyleFloatingPoint(NumberStyles style)
{
// Check for undefined flags or hex number
if ((style & (InvalidNumberStyles | NumberStyles.AllowHexSpecifier | NumberStyles.AllowBinarySpecifier)) != 0)
// Check for undefined flags
if ((style & InvalidNumberStyles) != 0)
{
ThrowInvalid(style);
ThrowInvalidStyle();
}

static void ThrowInvalid(NumberStyles value) =>
throw new ArgumentException((value & InvalidNumberStyles) != 0 ? SR.Argument_InvalidNumberStyles : SR.Arg_HexBinaryStylesNotSupported, nameof(style));
// Binary specifier is not supported for floating point
if ((style & NumberStyles.AllowBinarySpecifier) != 0)
{
ThrowHexBinaryStylesNotSupported();
}

// When AllowHexSpecifier is used, only specific flags are allowed
if ((style & NumberStyles.AllowHexSpecifier) != 0)
{
// HexFloat allows: AllowLeadingWhite, AllowTrailingWhite, AllowLeadingSign, AllowHexSpecifier, AllowDecimalPoint, AllowExponent
NumberStyles invalidFlags = style & ~NumberStyles.HexFloat;
if (invalidFlags != 0)
{
ThrowInvalidHexBinaryStyle();
}
}

[DoesNotReturn]
static void ThrowInvalidStyle() =>
throw new ArgumentException(SR.Argument_InvalidNumberStyles, nameof(style));

[DoesNotReturn]
static void ThrowHexBinaryStylesNotSupported() =>
throw new ArgumentException(SR.Arg_HexBinaryStylesNotSupported, nameof(style));

[DoesNotReturn]
static void ThrowInvalidHexBinaryStyle() =>
throw new ArgumentException(SR.Arg_InvalidHexBinaryStyle, nameof(style));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,9 @@ public enum NumberStyles
Float = AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign |
AllowDecimalPoint | AllowExponent,

/// <summary>Indicates that the <see cref="AllowLeadingWhite"/>, <see cref="AllowTrailingWhite"/>, <see cref="AllowLeadingSign"/>, <see cref="AllowHexSpecifier"/>, <see cref="AllowDecimalPoint"/>, and <see cref="AllowExponent"/> styles are used for hexadecimal floating-point values. This is a composite number style.</summary>
HexFloat = AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign | AllowHexSpecifier | AllowDecimalPoint | AllowExponent,

Currency = AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign | AllowTrailingSign |
AllowParentheses | AllowDecimalPoint | AllowThousands | AllowCurrencySymbol,

Expand Down
163 changes: 163 additions & 0 deletions src/libraries/System.Private.CoreLib/src/System/Number.Formatting.cs
Original file line number Diff line number Diff line change
Expand Up @@ -526,6 +526,162 @@ private static int GetFloatingPointMaxDigitsAndPrecision(char fmt, ref int preci
return maxDigits;
}

private static void FormatFloatAsHex<TNumber, TChar>(ref ValueListBuilder<TChar> vlb, TNumber value, char fmt, int precision)
where TNumber : unmanaged, IBinaryFloatParseAndFormatInfo<TNumber>
where TChar : unmanaged, IUtfChar<TChar>
{
// Get the raw bits
ulong bits = TNumber.FloatToBits(value);
int mantissaBits = TNumber.NormalMantissaBits;
int exponentBias = TNumber.ExponentBias;

// Extract sign, exponent, and mantissa
bool isNegative = (bits >> (mantissaBits + TNumber.ExponentBits)) != 0;
int biasedExponent = (int)((bits >> mantissaBits) & ((1UL << TNumber.ExponentBits) - 1));
ulong mantissa = bits & TNumber.NormalMantissaMask;

// Add sign
if (isNegative)
{
vlb.Append(TChar.CastFrom('-'));
}

// Add "0x" prefix
vlb.Append(TChar.CastFrom('0'));
vlb.Append(TChar.CastFrom(fmt)); // 'x' or 'X'

// Handle special cases
if (biasedExponent == TNumber.InfinityExponent)
{
// Infinity or NaN - just output as 0
vlb.Append(TChar.CastFrom('0'));
vlb.Append(TChar.CastFrom('p'));
vlb.Append(TChar.CastFrom('+'));
vlb.Append(TChar.CastFrom('0'));
return;
}

if (biasedExponent == 0 && mantissa == 0)
{
// Zero
vlb.Append(TChar.CastFrom('0'));
if (precision > 0)
{
vlb.Append(TChar.CastFrom('.'));
for (int i = 0; i < precision; i++)
{
vlb.Append(TChar.CastFrom('0'));
}
}
vlb.Append(TChar.CastFrom('p'));
vlb.Append(TChar.CastFrom('+'));
vlb.Append(TChar.CastFrom('0'));
return;
}

// Normalize mantissa for hex output (leading digit should be 1.xxx in range [1, 2))
int actualExponent;
ulong significand;

if (biasedExponent == 0)
{
// Denormal number - normalize by shifting until we get leading 1
significand = mantissa;
int lz = BitOperations.LeadingZeroCount(significand) - (64 - mantissaBits);
significand <<= lz;
actualExponent = 1 - exponentBias - lz;
}
else
{
// Normal number - add implicit leading bit
significand = (1UL << mantissaBits) | mantissa;
actualExponent = biasedExponent - exponentBias;
}

// Shift significand so the leading 1 is at bit 60 (first nibble position)
// This ensures the integer part is 1.xxx
int shift = 63 - mantissaBits;
significand <<= shift;

// Adjust exponent for the shift (we divided by 2^shift, so add shift to exponent)
// But we also want the leading nibble at bit 60, so shift right by 3 more
significand >>= 3;
actualExponent += 3;

// Output integer part (should always be 1 for normalized form)
char hexBase = fmt == 'X' ? 'A' : 'a';
int firstNibble = (int)(significand >> 60);
char firstHexChar = firstNibble < 10 ? (char)('0' + firstNibble) : (char)(hexBase + firstNibble - 10);
vlb.Append(TChar.CastFrom(firstHexChar));

// Remove the first nibble
significand <<= 4;

// Determine how many hex digits to output
int hexDigits = precision >= 0 ? precision : (mantissaBits + 3) / 4;

if (hexDigits > 0)
{
vlb.Append(TChar.CastFrom('.'));

for (int i = 0; i < hexDigits; i++)
{
int nibble = (int)(significand >> 60);
char hexChar = nibble < 10 ? (char)('0' + nibble) : (char)(hexBase + nibble - 10);
vlb.Append(TChar.CastFrom(hexChar));
significand <<= 4;
}
}

// Output exponent
vlb.Append(TChar.CastFrom('p'));
if (actualExponent >= 0)
{
vlb.Append(TChar.CastFrom('+'));
}

// Format exponent as decimal without allocating string
FormatInt32ToValueListBuilder(ref vlb, actualExponent);
}

private static void FormatInt32ToValueListBuilder<TChar>(ref ValueListBuilder<TChar> vlb, int value)
where TChar : unmanaged, IUtfChar<TChar>
{
if (value < 0)
{
vlb.Append(TChar.CastFrom('-'));
Copy link

Copilot AI Oct 12, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Potential integer overflow when negating int.MinValue. The negation of int.MinValue overflows and remains negative, which could cause incorrect behavior.

Suggested change
vlb.Append(TChar.CastFrom('-'));
vlb.Append(TChar.CastFrom('-'));
if (value == int.MinValue)
{
// int.MinValue cannot be negated; use its magnitude as uint
string numStr = ((uint)int.MinValue).ToString();
foreach (char c in numStr)
{
vlb.Append(TChar.CastFrom(c));
}
return;
}

Copilot uses AI. Check for mistakes.

value = -value;
}

// Handle zero specially
if (value == 0)
{
vlb.Append(TChar.CastFrom('0'));
return;
}

// Format digits in reverse, then reverse the span
int startIndex = vlb.Length;
uint uvalue = (uint)value;

while (uvalue > 0)
{
vlb.Append(TChar.CastFrom((char)('0' + (uvalue % 10))));
uvalue /= 10;
Comment on lines +669 to +670
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could use Math.DivRem.

}

// Reverse the digits
int endIndex = vlb.Length - 1;
while (startIndex < endIndex)
{
TChar temp = vlb[startIndex];
vlb[startIndex] = vlb[endIndex];
vlb[endIndex] = temp;
startIndex++;
endIndex--;
}
}

public static string FormatFloat<TNumber>(TNumber value, string? format, NumberFormatInfo info)
where TNumber : unmanaged, IBinaryFloatParseAndFormatInfo<TNumber>
{
Expand Down Expand Up @@ -598,6 +754,13 @@ public static bool TryFormatFloat<TNumber, TChar>(TNumber value, ReadOnlySpan<ch
precision = TNumber.MaxPrecisionCustomFormat;
}

// Handle hex float formatting (X or x)
if (fmt == 'X' || fmt == 'x')
{
FormatFloatAsHex(ref vlb, value, fmt, precision);
return null;
}

NumberBuffer number = new NumberBuffer(NumberBufferKind.FloatingPoint, pDigits, TNumber.NumberBufferLength);
number.IsNegative = TNumber.IsNegative(value);

Expand Down
Loading
Loading