1

I want to display a three bytes (signed) in C#.

The code (fragment) I made is:

case 3:
   HexadecimalValueRange = SignedValueChecked ?
     string.Format("{0:X6}..{1:X6}", (Int32) minValue, (Int32) maxValue)
    : string.Format("{0:X6}..{1:X6}", (UInt32)minValue, (UInt32)maxValue);

But it displays an example negative value as 0xFFC00000 where I would like to see 0xC000000, so with 6 'significant' digits (thus without the leading FF).

Michel Keijzers
  • 15,025
  • 28
  • 93
  • 119
  • 1
    According to [Standard Numeric Format Strings](https://msdn.microsoft.com/en-us/library/dwhawy9k%28v=vs.110%29.aspx#XFormatString), the precision specifier *indicates the **minimum** number of digits desired in the resulting string.* It's not the max number, and it won't clamp the number, as shown in the example: `123456789.ToString("X2") // Displays 75BCD15`. Try [How to force a number to be in a range in C#?](http://stackoverflow.com/questions/3176602/how-to-force-a-number-to-be-in-a-range-in-c) instead. – dbc Sep 06 '15 at 20:51
  • @dbc: I know that it is the minimum number of digits, however clamping the value still would result in leading FF values. – Michel Keijzers Sep 06 '15 at 20:59

1 Answers1

2

The leading bits of negative number are significant, so you can't cut the off with String.Format (there is no specifier that let you ignore significant digits, width specify only minimum size and left/right justification).

You can convert the values to 3-byte uint to print them the way you want:

string.Format("{0,-6:X}",(uint)(int.MaxValue & 0xFFFFFF)) 
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179