/
Half.cs
2008 lines (1646 loc) · 92.1 KB
/
Half.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Buffers.Binary;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System
{
// Portions of the code implemented below are based on the 'Berkeley SoftFloat Release 3e' algorithms.
/// <summary>
/// An IEEE 754 compliant float16 type.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public readonly struct Half
: IComparable,
ISpanFormattable,
IComparable<Half>,
IEquatable<Half>,
IBinaryFloatingPointIeee754<Half>,
IMinMaxValue<Half>
{
private const NumberStyles DefaultParseStyle = NumberStyles.Float | NumberStyles.AllowThousands;
// Constants for manipulating the private bit-representation
internal const ushort SignMask = 0x8000;
internal const int SignShift = 15;
internal const byte ShiftedSignMask = SignMask >> SignShift;
internal const ushort BiasedExponentMask = 0x7C00;
internal const int BiasedExponentShift = 10;
internal const byte ShiftedBiasedExponentMask = BiasedExponentMask >> BiasedExponentShift;
internal const ushort TrailingSignificandMask = 0x03FF;
internal const byte MinSign = 0;
internal const byte MaxSign = 1;
internal const byte MinBiasedExponent = 0x00;
internal const byte MaxBiasedExponent = 0x1F;
internal const byte ExponentBias = 15;
internal const sbyte MinExponent = -14;
internal const sbyte MaxExponent = +15;
internal const ushort MinTrailingSignificand = 0x0000;
internal const ushort MaxTrailingSignificand = 0x03FF;
// Constants representing the private bit-representation for various default values
private const ushort PositiveZeroBits = 0x0000;
private const ushort NegativeZeroBits = 0x8000;
private const ushort EpsilonBits = 0x0001;
private const ushort PositiveInfinityBits = 0x7C00;
private const ushort NegativeInfinityBits = 0xFC00;
private const ushort PositiveQNaNBits = 0x7E00;
private const ushort NegativeQNaNBits = 0xFE00;
private const ushort MinValueBits = 0xFBFF;
private const ushort MaxValueBits = 0x7BFF;
private const ushort PositiveOneBits = 0x3C00;
private const ushort NegativeOneBits = 0xBC00;
private const ushort EBits = 0x4170;
private const ushort PiBits = 0x4248;
private const ushort TauBits = 0x4648;
// Well-defined and commonly used values
public static Half Epsilon => new Half(EpsilonBits); // 5.9604645E-08
public static Half PositiveInfinity => new Half(PositiveInfinityBits); // 1.0 / 0.0;
public static Half NegativeInfinity => new Half(NegativeInfinityBits); // -1.0 / 0.0
public static Half NaN => new Half(NegativeQNaNBits); // 0.0 / 0.0
/// <inheritdoc cref="IMinMaxValue{TSelf}.MinValue" />
public static Half MinValue => new Half(MinValueBits); // -65504
/// <inheritdoc cref="IMinMaxValue{TSelf}.MaxValue" />
public static Half MaxValue => new Half(MaxValueBits); // 65504
internal readonly ushort _value;
internal Half(ushort value)
{
_value = value;
}
private Half(bool sign, ushort exp, ushort sig) => _value = (ushort)(((sign ? 1 : 0) << SignShift) + (exp << BiasedExponentShift) + sig);
internal byte BiasedExponent
{
get
{
ushort bits = _value;
return ExtractBiasedExponentFromBits(bits);
}
}
internal sbyte Exponent
{
get
{
return (sbyte)(BiasedExponent - ExponentBias);
}
}
internal ushort Significand
{
get
{
return (ushort)(TrailingSignificand | ((BiasedExponent != 0) ? (1U << BiasedExponentShift) : 0U));
}
}
internal ushort TrailingSignificand
{
get
{
ushort bits = _value;
return ExtractTrailingSignificandFromBits(bits);
}
}
internal static byte ExtractBiasedExponentFromBits(ushort bits)
{
return (byte)((bits >> BiasedExponentShift) & ShiftedBiasedExponentMask);
}
internal static ushort ExtractTrailingSignificandFromBits(ushort bits)
{
return (ushort)(bits & TrailingSignificandMask);
}
/// <inheritdoc cref="IComparisonOperators{TSelf, TOther, TResult}.op_LessThan(TSelf, TOther)" />
public static bool operator <(Half left, Half right)
{
if (IsNaN(left) || IsNaN(right))
{
// IEEE defines that NaN is unordered with respect to everything, including itself.
return false;
}
bool leftIsNegative = IsNegative(left);
if (leftIsNegative != IsNegative(right))
{
// When the signs of left and right differ, we know that left is less than right if it is
// the negative value. The exception to this is if both values are zero, in which case IEEE
// says they should be equal, even if the signs differ.
return leftIsNegative && !AreZero(left, right);
}
return (left._value != right._value) && ((left._value < right._value) ^ leftIsNegative);
}
/// <inheritdoc cref="IComparisonOperators{TSelf, TOther, TResult}.op_GreaterThan(TSelf, TOther)" />
public static bool operator >(Half left, Half right)
{
return right < left;
}
/// <inheritdoc cref="IComparisonOperators{TSelf, TOther, TResult}.op_LessThanOrEqual(TSelf, TOther)" />
public static bool operator <=(Half left, Half right)
{
if (IsNaN(left) || IsNaN(right))
{
// IEEE defines that NaN is unordered with respect to everything, including itself.
return false;
}
bool leftIsNegative = IsNegative(left);
if (leftIsNegative != IsNegative(right))
{
// When the signs of left and right differ, we know that left is less than right if it is
// the negative value. The exception to this is if both values are zero, in which case IEEE
// says they should be equal, even if the signs differ.
return leftIsNegative || AreZero(left, right);
}
return (left._value == right._value) || ((left._value < right._value) ^ leftIsNegative);
}
/// <inheritdoc cref="IComparisonOperators{TSelf, TOther, TResult}.op_GreaterThanOrEqual(TSelf, TOther)" />
public static bool operator >=(Half left, Half right)
{
return right <= left;
}
/// <inheritdoc cref="IEqualityOperators{TSelf, TOther, TResult}.op_Equality(TSelf, TOther)" />
public static bool operator ==(Half left, Half right)
{
if (IsNaN(left) || IsNaN(right))
{
// IEEE defines that NaN is not equal to anything, including itself.
return false;
}
// IEEE defines that positive and negative zero are equivalent.
return (left._value == right._value) || AreZero(left, right);
}
/// <inheritdoc cref="IEqualityOperators{TSelf, TOther, TResult}.op_Inequality(TSelf, TOther)" />
public static bool operator !=(Half left, Half right)
{
return !(left == right);
}
/// <summary>Determines whether the specified value is finite (zero, subnormal, or normal).</summary>
public static bool IsFinite(Half value)
{
return StripSign(value) < PositiveInfinityBits;
}
/// <summary>Determines whether the specified value is infinite.</summary>
public static bool IsInfinity(Half value)
{
return StripSign(value) == PositiveInfinityBits;
}
/// <summary>Determines whether the specified value is NaN.</summary>
public static bool IsNaN(Half value)
{
return StripSign(value) > PositiveInfinityBits;
}
/// <summary>Determines whether the specified value is negative.</summary>
public static bool IsNegative(Half value)
{
return (short)(value._value) < 0;
}
/// <summary>Determines whether the specified value is negative infinity.</summary>
public static bool IsNegativeInfinity(Half value)
{
return value._value == NegativeInfinityBits;
}
/// <summary>Determines whether the specified value is normal.</summary>
// This is probably not worth inlining, it has branches and should be rarely called
public static bool IsNormal(Half value)
{
uint absValue = StripSign(value);
return (absValue < PositiveInfinityBits) // is finite
&& (absValue != 0) // is not zero
&& ((absValue & BiasedExponentMask) != 0); // is not subnormal (has a non-zero exponent)
}
/// <summary>Determines whether the specified value is positive infinity.</summary>
public static bool IsPositiveInfinity(Half value)
{
return value._value == PositiveInfinityBits;
}
/// <summary>Determines whether the specified value is subnormal.</summary>
// This is probably not worth inlining, it has branches and should be rarely called
public static bool IsSubnormal(Half value)
{
uint absValue = StripSign(value);
return (absValue < PositiveInfinityBits) // is finite
&& (absValue != 0) // is not zero
&& ((absValue & BiasedExponentMask) == 0); // is subnormal (has a zero exponent)
}
/// <summary>
/// Parses a <see cref="Half"/> from a <see cref="string"/> in the default parse style.
/// </summary>
/// <param name="s">The input to be parsed.</param>
/// <returns>The equivalent <see cref="Half"/> value representing the input string. If the input exceeds Half's range, a <see cref="Half.PositiveInfinity"/> or <see cref="Half.NegativeInfinity"/> is returned. </returns>
public static Half Parse(string s)
{
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseHalf(s, DefaultParseStyle, NumberFormatInfo.CurrentInfo);
}
/// <summary>
/// Parses a <see cref="Half"/> from a <see cref="string"/> in the given <see cref="NumberStyles"/>.
/// </summary>
/// <param name="s">The input to be parsed.</param>
/// <param name="style">The <see cref="NumberStyles"/> used to parse the input.</param>
/// <returns>The equivalent <see cref="Half"/> value representing the input string. If the input exceeds Half's range, a <see cref="Half.PositiveInfinity"/> or <see cref="Half.NegativeInfinity"/> is returned. </returns>
public static Half Parse(string s, NumberStyles style)
{
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseHalf(s, style, NumberFormatInfo.CurrentInfo);
}
/// <summary>
/// Parses a <see cref="Half"/> from a <see cref="string"/> and <see cref="IFormatProvider"/>.
/// </summary>
/// <param name="s">The input to be parsed.</param>
/// <param name="provider">A format provider.</param>
/// <returns>The equivalent <see cref="Half"/> value representing the input string. If the input exceeds Half's range, a <see cref="Half.PositiveInfinity"/> or <see cref="Half.NegativeInfinity"/> is returned. </returns>
public static Half Parse(string s, IFormatProvider? provider)
{
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseHalf(s, DefaultParseStyle, NumberFormatInfo.GetInstance(provider));
}
/// <summary>
/// Parses a <see cref="Half"/> from a <see cref="string"/> with the given <see cref="NumberStyles"/> and <see cref="IFormatProvider"/>.
/// </summary>
/// <param name="s">The input to be parsed.</param>
/// <param name="style">The <see cref="NumberStyles"/> used to parse the input.</param>
/// <param name="provider">A format provider.</param>
/// <returns>The equivalent <see cref="Half"/> value representing the input string. If the input exceeds Half's range, a <see cref="Half.PositiveInfinity"/> or <see cref="Half.NegativeInfinity"/> is returned. </returns>
public static Half Parse(string s, NumberStyles style = DefaultParseStyle, IFormatProvider? provider = null)
{
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseHalf(s, style, NumberFormatInfo.GetInstance(provider));
}
/// <summary>
/// Parses a <see cref="Half"/> from a <see cref="ReadOnlySpan{Char}"/> and <see cref="IFormatProvider"/>.
/// </summary>
/// <param name="s">The input to be parsed.</param>
/// <param name="style">The <see cref="NumberStyles"/> used to parse the input.</param>
/// <param name="provider">A format provider. </param>
/// <returns>The equivalent <see cref="Half"/> value representing the input string. If the input exceeds Half's range, a <see cref="Half.PositiveInfinity"/> or <see cref="Half.NegativeInfinity"/> is returned. </returns>
public static Half Parse(ReadOnlySpan<char> s, NumberStyles style = DefaultParseStyle, IFormatProvider? provider = null)
{
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
return Number.ParseHalf(s, style, NumberFormatInfo.GetInstance(provider));
}
/// <summary>
/// Tries to parses a <see cref="Half"/> from a <see cref="string"/> in the default parse style.
/// </summary>
/// <param name="s">The input to be parsed.</param>
/// <param name="result">The equivalent <see cref="Half"/> value representing the input string if the parse was successful. If the input exceeds Half's range, a <see cref="Half.PositiveInfinity"/> or <see cref="Half.NegativeInfinity"/> is returned. If the parse was unsuccessful, a default <see cref="Half"/> value is returned.</param>
/// <returns><see langword="true" /> if the parse was successful, <see langword="false" /> otherwise.</returns>
public static bool TryParse([NotNullWhen(true)] string? s, out Half result)
{
if (s == null)
{
result = default;
return false;
}
return TryParse(s, DefaultParseStyle, provider: null, out result);
}
/// <summary>
/// Tries to parses a <see cref="Half"/> from a <see cref="ReadOnlySpan{Char}"/> in the default parse style.
/// </summary>
/// <param name="s">The input to be parsed.</param>
/// <param name="result">The equivalent <see cref="Half"/> value representing the input string if the parse was successful. If the input exceeds Half's range, a <see cref="Half.PositiveInfinity"/> or <see cref="Half.NegativeInfinity"/> is returned. If the parse was unsuccessful, a default <see cref="Half"/> value is returned.</param>
/// <returns><see langword="true" /> if the parse was successful, <see langword="false" /> otherwise.</returns>
public static bool TryParse(ReadOnlySpan<char> s, out Half result)
{
return TryParse(s, DefaultParseStyle, provider: null, out result);
}
/// <summary>
/// Tries to parse a <see cref="Half"/> from a <see cref="string"/> with the given <see cref="NumberStyles"/> and <see cref="IFormatProvider"/>.
/// </summary>
/// <param name="s">The input to be parsed.</param>
/// <param name="style">The <see cref="NumberStyles"/> used to parse the input.</param>
/// <param name="provider">A format provider. </param>
/// <param name="result">The equivalent <see cref="Half"/> value representing the input string if the parse was successful. If the input exceeds Half's range, a <see cref="Half.PositiveInfinity"/> or <see cref="Half.NegativeInfinity"/> is returned. If the parse was unsuccessful, a default <see cref="Half"/> value is returned.</param>
/// <returns><see langword="true" /> if the parse was successful, <see langword="false" /> otherwise.</returns>
public static bool TryParse([NotNullWhen(true)] string? s, NumberStyles style, IFormatProvider? provider, out Half result)
{
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
if (s == null)
{
result = default;
return false;
}
return TryParse(s.AsSpan(), style, provider, out result);
}
/// <summary>
/// Tries to parse a <see cref="Half"/> from a <see cref="ReadOnlySpan{Char}"/> with the given <see cref="NumberStyles"/> and <see cref="IFormatProvider"/>.
/// </summary>
/// <param name="s">The input to be parsed.</param>
/// <param name="style">The <see cref="NumberStyles"/> used to parse the input.</param>
/// <param name="provider">A format provider. </param>
/// <param name="result">The equivalent <see cref="Half"/> value representing the input string if the parse was successful. If the input exceeds Half's range, a <see cref="Half.PositiveInfinity"/> or <see cref="Half.NegativeInfinity"/> is returned. If the parse was unsuccessful, a default <see cref="Half"/> value is returned.</param>
/// <returns><see langword="true" /> if the parse was successful, <see langword="false" /> otherwise.</returns>
public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider? provider, out Half result)
{
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
return Number.TryParseHalf(s, style, NumberFormatInfo.GetInstance(provider), out result);
}
private static bool AreZero(Half left, Half right)
{
// IEEE defines that positive and negative zero are equal, this gives us a quick equality check
// for two values by or'ing the private bits together and stripping the sign. They are both zero,
// and therefore equivalent, if the resulting value is still zero.
return (ushort)((left._value | right._value) & ~SignMask) == 0;
}
private static bool IsNaNOrZero(Half value)
{
return ((value._value - 1) & ~SignMask) >= PositiveInfinityBits;
}
private static uint StripSign(Half value)
{
return (ushort)(value._value & ~SignMask);
}
/// <summary>
/// Compares this object to another object, returning an integer that indicates the relationship.
/// </summary>
/// <returns>A value less than zero if this is less than <paramref name="obj"/>, zero if this is equal to <paramref name="obj"/>, or a value greater than zero if this is greater than <paramref name="obj"/>.</returns>
/// <exception cref="ArgumentException">Thrown when <paramref name="obj"/> is not of type <see cref="Half"/>.</exception>
public int CompareTo(object? obj)
{
if (!(obj is Half))
{
return (obj is null) ? 1 : throw new ArgumentException(SR.Arg_MustBeHalf);
}
return CompareTo((Half)(obj));
}
/// <summary>
/// Compares this object to another object, returning an integer that indicates the relationship.
/// </summary>
/// <returns>A value less than zero if this is less than <paramref name="other"/>, zero if this is equal to <paramref name="other"/>, or a value greater than zero if this is greater than <paramref name="other"/>.</returns>
public int CompareTo(Half other)
{
if (this < other)
{
return -1;
}
if (this > other)
{
return 1;
}
if (this == other)
{
return 0;
}
if (IsNaN(this))
{
return IsNaN(other) ? 0 : -1;
}
Debug.Assert(IsNaN(other));
return 1;
}
/// <summary>
/// Returns a value that indicates whether this instance is equal to a specified <paramref name="obj"/>.
/// </summary>
public override bool Equals([NotNullWhen(true)] object? obj)
{
return (obj is Half other) && Equals(other);
}
/// <summary>
/// Returns a value that indicates whether this instance is equal to a specified <paramref name="other"/> value.
/// </summary>
public bool Equals(Half other)
{
return _value == other._value
|| AreZero(this, other)
|| (IsNaN(this) && IsNaN(other));
}
/// <summary>
/// Serves as the default hash function.
/// </summary>
public override int GetHashCode()
{
if (IsNaNOrZero(this))
{
// All NaNs should have the same hash code, as should both Zeros.
return _value & PositiveInfinityBits;
}
return _value;
}
/// <summary>
/// Returns a string representation of the current value.
/// </summary>
public override string ToString()
{
return Number.FormatHalf(this, null, NumberFormatInfo.CurrentInfo);
}
/// <summary>
/// Returns a string representation of the current value using the specified <paramref name="format"/>.
/// </summary>
public string ToString([StringSyntax(StringSyntaxAttribute.NumericFormat)] string? format)
{
return Number.FormatHalf(this, format, NumberFormatInfo.CurrentInfo);
}
/// <summary>
/// Returns a string representation of the current value with the specified <paramref name="provider"/>.
/// </summary>
public string ToString(IFormatProvider? provider)
{
return Number.FormatHalf(this, null, NumberFormatInfo.GetInstance(provider));
}
/// <summary>
/// Returns a string representation of the current value using the specified <paramref name="format"/> and <paramref name="provider"/>.
/// </summary>
public string ToString([StringSyntax(StringSyntaxAttribute.NumericFormat)] string? format, IFormatProvider? provider)
{
return Number.FormatHalf(this, format, NumberFormatInfo.GetInstance(provider));
}
/// <summary>
/// Tries to format the value of the current Half instance into the provided span of characters.
/// </summary>
/// <param name="destination">When this method returns, this instance's value formatted as a span of characters.</param>
/// <param name="charsWritten">When this method returns, the number of characters that were written in <paramref name="destination"/>.</param>
/// <param name="format">A span containing the characters that represent a standard or custom format string that defines the acceptable format for <paramref name="destination"/>.</param>
/// <param name="provider">An optional object that supplies culture-specific formatting information for <paramref name="destination"/>.</param>
/// <returns></returns>
public bool TryFormat(Span<char> destination, out int charsWritten, [StringSyntax(StringSyntaxAttribute.NumericFormat)] ReadOnlySpan<char> format = default, IFormatProvider? provider = null)
{
return Number.TryFormatHalf(this, format, NumberFormatInfo.GetInstance(provider), destination, out charsWritten);
}
//
// Explicit Convert To Half
//
/// <summary>Explicitly converts a <see cref="char" /> value to its nearest representable half-precision floating-point value.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to its nearest representable half-precision floating-point value.</returns>
public static explicit operator Half(char value) => (Half)(float)value;
/// <summary>Explicitly converts a <see cref="decimal" /> value to its nearest representable half-precision floating-point value.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to its nearest representable half-precision floating-point value.</returns>
public static explicit operator Half(decimal value) => (Half)(float)value;
/// <summary>Explicitly converts a <see cref="double" /> value to its nearest representable half-precision floating-point value.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to its nearest representable half-precision floating-point value.</returns>
public static explicit operator Half(double value)
{
const int DoubleMaxExponent = 0x7FF;
ulong doubleInt = BitConverter.DoubleToUInt64Bits(value);
bool sign = (doubleInt & double.SignMask) >> double.SignShift != 0;
int exp = (int)((doubleInt & double.BiasedExponentMask) >> double.BiasedExponentShift);
ulong sig = doubleInt & double.TrailingSignificandMask;
if (exp == DoubleMaxExponent)
{
if (sig != 0) // NaN
{
return CreateHalfNaN(sign, sig << 12); // Shift the significand bits to the left end
}
return sign ? NegativeInfinity : PositiveInfinity;
}
uint sigHalf = (uint)ShiftRightJam(sig, 38);
if ((exp | (int)sigHalf) == 0)
{
return new Half(sign, 0, 0);
}
return new Half(RoundPackToHalf(sign, (short)(exp - 0x3F1), (ushort)(sigHalf | 0x4000)));
}
/// <summary>Explicitly converts a <see cref="short" /> value to its nearest representable half-precision floating-point value.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to its nearest representable half-precision floating-point value.</returns>
public static explicit operator Half(short value) => (Half)(float)value;
/// <summary>Explicitly converts a <see cref="int" /> value to its nearest representable half-precision floating-point value.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to its nearest representable half-precision floating-point value.</returns>
public static explicit operator Half(int value) => (Half)(float)value;
/// <summary>Explicitly converts a <see cref="long" /> value to its nearest representable half-precision floating-point value.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to its nearest representable half-precision floating-point value.</returns>
public static explicit operator Half(long value) => (Half)(float)value;
/// <summary>Explicitly converts a <see cref="System.IntPtr" /> value to its nearest representable half-precision floating-point value.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to its nearest representable half-precision floating-point value.</returns>
public static explicit operator Half(nint value) => (Half)(float)value;
/// <summary>Explicitly converts a <see cref="float" /> value to its nearest representable half-precision floating-point value.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to its nearest representable half-precision floating-point value.</returns>
public static explicit operator Half(float value)
{
const int SingleMaxExponent = 0xFF;
uint floatInt = BitConverter.SingleToUInt32Bits(value);
bool sign = (floatInt & float.SignMask) >> float.SignShift != 0;
int exp = (int)(floatInt & float.BiasedExponentMask) >> float.BiasedExponentShift;
uint sig = floatInt & float.TrailingSignificandMask;
if (exp == SingleMaxExponent)
{
if (sig != 0) // NaN
{
return CreateHalfNaN(sign, (ulong)sig << 41); // Shift the significand bits to the left end
}
return sign ? NegativeInfinity : PositiveInfinity;
}
uint sigHalf = sig >> 9 | ((sig & 0x1FFU) != 0 ? 1U : 0U); // RightShiftJam
if ((exp | (int)sigHalf) == 0)
{
return new Half(sign, 0, 0);
}
return new Half(RoundPackToHalf(sign, (short)(exp - 0x71), (ushort)(sigHalf | 0x4000)));
}
/// <summary>Explicitly converts a <see cref="ushort" /> value to its nearest representable half-precision floating-point value.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to its nearest representable half-precision floating-point value.</returns>
[CLSCompliant(false)]
public static explicit operator Half(ushort value) => (Half)(float)value;
/// <summary>Explicitly converts a <see cref="uint" /> value to its nearest representable half-precision floating-point value.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to its nearest representable half-precision floating-point value.</returns>
[CLSCompliant(false)]
public static explicit operator Half(uint value) => (Half)(float)value;
/// <summary>Explicitly converts a <see cref="ulong" /> value to its nearest representable half-precision floating-point value.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to its nearest representable half-precision floating-point value.</returns>
[CLSCompliant(false)]
public static explicit operator Half(ulong value) => (Half)(float)value;
/// <summary>Explicitly converts a <see cref="System.UIntPtr" /> value to its nearest representable half-precision floating-point value.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to its nearest representable half-precision floating-point value.</returns>
[CLSCompliant(false)]
public static explicit operator Half(nuint value) => (Half)(float)value;
//
// Explicit Convert From Half
//
/// <summary>Explicitly converts a half-precision floating-point value to its nearest representable <see cref="byte" /> value.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to its nearest representable <see cref="byte" /> value.</returns>
public static explicit operator byte(Half value) => (byte)(float)value;
/// <summary>Explicitly converts a half-precision floating-point value to its nearest representable <see cref="byte" /> value, throwing an overflow exception for any values that fall outside the representable range.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to its nearest representable <see cref="byte" /> value.</returns>
/// <exception cref="OverflowException"><paramref name="value" /> is not representable by <see cref="byte" />.</exception>
public static explicit operator checked byte(Half value) => checked((byte)(float)value);
/// <summary>Explicitly converts a half-precision floating-point value to its nearest representable <see cref="char" /> value.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to its nearest representable <see cref="char" /> value.</returns>
public static explicit operator char(Half value) => (char)(float)value;
/// <summary>Explicitly converts a half-precision floating-point value to its nearest representable <see cref="char" /> value, throwing an overflow exception for any values that fall outside the representable range.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to its nearest representable <see cref="char" /> value.</returns>
/// <exception cref="OverflowException"><paramref name="value" /> is not representable by <see cref="char" />.</exception>
public static explicit operator checked char(Half value) => checked((char)(float)value);
/// <summary>Explicitly converts a half-precision floating-point value to its nearest representable <see cref="decimal" /> value.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to its nearest representable <see cref="decimal" /> value.</returns>
public static explicit operator decimal(Half value) => (decimal)(float)value;
/// <summary>Explicitly converts a half-precision floating-point value to its nearest representable <see cref="short" /> value.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to its nearest representable <see cref="short" /> value.</returns>
public static explicit operator short(Half value) => (short)(float)value;
/// <summary>Explicitly converts a half-precision floating-point value to its nearest representable <see cref="short" /> value, throwing an overflow exception for any values that fall outside the representable range.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to its nearest representable <see cref="short" /> value.</returns>
/// <exception cref="OverflowException"><paramref name="value" /> is not representable by <see cref="short" />.</exception>
public static explicit operator checked short(Half value) => checked((short)(float)value);
/// <summary>Explicitly converts a half-precision floating-point value to its nearest representable <see cref="int" /> value.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to its nearest representable <see cref="int" /> value.</returns>
public static explicit operator int(Half value) => (int)(float)value;
/// <summary>Explicitly converts a half-precision floating-point value to its nearest representable <see cref="int" /> value, throwing an overflow exception for any values that fall outside the representable range.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to its nearest representable <see cref="int" /> value.</returns>
/// <exception cref="OverflowException"><paramref name="value" /> is not representable by <see cref="int" />.</exception>
public static explicit operator checked int(Half value) => checked((int)(float)value);
/// <summary>Explicitly converts a half-precision floating-point value to its nearest representable <see cref="long" /> value.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to its nearest representable <see cref="long" /> value.</returns>
public static explicit operator long(Half value) => (long)(float)value;
/// <summary>Explicitly converts a half-precision floating-point value to its nearest representable <see cref="long" /> value, throwing an overflow exception for any values that fall outside the representable range.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to its nearest representable <see cref="long" /> value.</returns>
/// <exception cref="OverflowException"><paramref name="value" /> is not representable by <see cref="long" />.</exception>
public static explicit operator checked long(Half value) => checked((long)(float)value);
/// <summary>Explicitly converts a half-precision floating-point value to its nearest representable <see cref="Int128"/>.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to a 128-bit signed integer.</returns>
public static explicit operator Int128(Half value) => (Int128)(double)(value);
/// <summary>Explicitly converts a half-precision floating-point value to its nearest representable <see cref="Int128"/>, throwing an overflow exception for any values that fall outside the representable range.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to a 128-bit signed integer.</returns>
/// <exception cref="OverflowException"><paramref name="value" /> is not representable by <see cref="Int128" />.</exception>
public static explicit operator checked Int128(Half value) => checked((Int128)(double)(value));
/// <summary>Explicitly converts a half-precision floating-point value to its nearest representable <see cref="IntPtr" /> value.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to its nearest representable <see cref="IntPtr" /> value.</returns>
public static explicit operator nint(Half value) => (nint)(float)value;
/// <summary>Explicitly converts a half-precision floating-point value to its nearest representable <see cref="IntPtr" /> value, throwing an overflow exception for any values that fall outside the representable range.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to its nearest representable <see cref="IntPtr" /> value.</returns>
/// <exception cref="OverflowException"><paramref name="value" /> is not representable by <see cref="IntPtr" />.</exception>
public static explicit operator checked nint(Half value) => checked((nint)(float)value);
/// <summary>Explicitly converts a half-precision floating-point value to its nearest representable <see cref="sbyte" /> value.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to its nearest representable <see cref="sbyte" /> value.</returns>
[CLSCompliant(false)]
public static explicit operator sbyte(Half value) => (sbyte)(float)value;
/// <summary>Explicitly converts a half-precision floating-point value to its nearest representable <see cref="sbyte" /> value, throwing an overflow exception for any values that fall outside the representable range.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to its nearest representable <see cref="sbyte" /> value.</returns>
/// <exception cref="OverflowException"><paramref name="value" /> is not representable by <see cref="sbyte" />.</exception>
[CLSCompliant(false)]
public static explicit operator checked sbyte(Half value) => checked((sbyte)(float)value);
/// <summary>Explicitly converts a half-precision floating-point value to its nearest representable <see cref="ushort" /> value.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to its nearest representable <see cref="ushort" /> value.</returns>
[CLSCompliant(false)]
public static explicit operator ushort(Half value) => (ushort)(float)value;
/// <summary>Explicitly converts a half-precision floating-point value to its nearest representable <see cref="ushort" /> value, throwing an overflow exception for any values that fall outside the representable range.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to its nearest representable <see cref="ushort" /> value.</returns>
/// <exception cref="OverflowException"><paramref name="value" /> is not representable by <see cref="ushort" />.</exception>
[CLSCompliant(false)]
public static explicit operator checked ushort(Half value) => checked((ushort)(float)value);
/// <summary>Explicitly converts a half-precision floating-point value to its nearest representable <see cref="uint" /> value.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to its nearest representable <see cref="uint" /> value.</returns>
[CLSCompliant(false)]
public static explicit operator uint(Half value) => (uint)(float)value;
/// <summary>Explicitly converts a half-precision floating-point value to its nearest representable <see cref="uint" /> value, throwing an overflow exception for any values that fall outside the representable range.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to its nearest representable <see cref="uint" /> value.</returns>
/// <exception cref="OverflowException"><paramref name="value" /> is not representable by <see cref="uint" />.</exception>
[CLSCompliant(false)]
public static explicit operator checked uint(Half value) => checked((uint)(float)value);
/// <summary>Explicitly converts a half-precision floating-point value to its nearest representable <see cref="ulong" /> value.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to its nearest representable <see cref="ulong" /> value.</returns>
[CLSCompliant(false)]
public static explicit operator ulong(Half value) => (ulong)(float)value;
/// <summary>Explicitly converts a half-precision floating-point value to its nearest representable <see cref="ulong" /> value, throwing an overflow exception for any values that fall outside the representable range.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to its nearest representable <see cref="ulong" /> value.</returns>
/// <exception cref="OverflowException"><paramref name="value" /> is not representable by <see cref="ulong" />.</exception>
[CLSCompliant(false)]
public static explicit operator checked ulong(Half value) => checked((ulong)(float)value);
/// <summary>Explicitly converts a half-precision floating-point value to its nearest representable <see cref="UInt128"/>.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to a 128-bit unsigned integer.</returns>
[CLSCompliant(false)]
public static explicit operator UInt128(Half value) => (UInt128)(double)(value);
/// <summary>Explicitly converts a half-precision floating-point value to its nearest representable <see cref="UInt128"/>, throwing an overflow exception for any values that fall outside the representable range.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to a 128-bit unsigned integer.</returns>
/// <exception cref="OverflowException"><paramref name="value" /> is not representable by <see cref="UInt128" />.</exception>
[CLSCompliant(false)]
public static explicit operator checked UInt128(Half value) => checked((UInt128)(double)(value));
/// <summary>Explicitly converts a half-precision floating-point value to its nearest representable <see cref="UIntPtr" /> value.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to its nearest representable <see cref="UIntPtr" /> value.</returns>
[CLSCompliant(false)]
public static explicit operator nuint(Half value) => (nuint)(float)value;
/// <summary>Explicitly converts a half-precision floating-point value to its nearest representable <see cref="UIntPtr" /> value, throwing an overflow exception for any values that fall outside the representable range.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to its nearest representable <see cref="UIntPtr" /> value.</returns>
/// <exception cref="OverflowException"><paramref name="value" /> is not representable by <see cref="UIntPtr" />.</exception>
[CLSCompliant(false)]
public static explicit operator checked nuint(Half value) => checked((nuint)(float)value);
//
// Implicit Convert To Half
//
/// <summary>Implicitly converts a <see cref="byte" /> value to its nearest representable half-precision floating-point value.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to its nearest representable half-precision floating-point value.</returns>
public static implicit operator Half(byte value) => (Half)(float)value;
/// <summary>Implicitly converts a <see cref="sbyte" /> value to its nearest representable half-precision floating-point value.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to its nearest representable half-precision floating-point value.</returns>
[CLSCompliant(false)]
public static implicit operator Half(sbyte value) => (Half)(float)value;
//
// Implicit Convert From Half (actually explicit due to back-compat)
//
/// <summary>Explicitly converts a half-precision floating-point value to its nearest representable <see cref="double" /> value.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to its nearest representable <see cref="double" /> value.</returns>
public static explicit operator double(Half value)
{
bool sign = IsNegative(value);
int exp = value.BiasedExponent;
uint sig = value.TrailingSignificand;
if (exp == MaxBiasedExponent)
{
if (sig != 0)
{
return CreateDoubleNaN(sign, (ulong)sig << 54);
}
return sign ? double.NegativeInfinity : double.PositiveInfinity;
}
if (exp == 0)
{
if (sig == 0)
{
return BitConverter.UInt64BitsToDouble(sign ? double.SignMask : 0); // Positive / Negative zero
}
(exp, sig) = NormSubnormalF16Sig(sig);
exp -= 1;
}
return CreateDouble(sign, (ushort)(exp + 0x3F0), (ulong)sig << 42);
}
/// <summary>Explicitly converts a half-precision floating-point value to its nearest representable <see cref="float" /> value.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to its nearest representable <see cref="float" /> value.</returns>
public static explicit operator float(Half value)
{
bool sign = IsNegative(value);
int exp = value.BiasedExponent;
uint sig = value.TrailingSignificand;
if (exp == MaxBiasedExponent)
{
if (sig != 0)
{
return CreateSingleNaN(sign, (ulong)sig << 54);
}
return sign ? float.NegativeInfinity : float.PositiveInfinity;
}
if (exp == 0)
{
if (sig == 0)
{
return BitConverter.UInt32BitsToSingle(sign ? float.SignMask : 0); // Positive / Negative zero
}
(exp, sig) = NormSubnormalF16Sig(sig);
exp -= 1;
}
return CreateSingle(sign, (byte)(exp + 0x70), sig << 13);
}
// IEEE 754 specifies NaNs to be propagated
internal static Half Negate(Half value)
{
return IsNaN(value) ? value : new Half((ushort)(value._value ^ SignMask));
}
private static (int Exp, uint Sig) NormSubnormalF16Sig(uint sig)
{
int shiftDist = BitOperations.LeadingZeroCount(sig) - 16 - 5;
return (1 - shiftDist, sig << shiftDist);
}
#region Utilities
// Significand bits should be shifted towards to the left end before calling these methods
// Creates Quiet NaN if significand == 0
private static Half CreateHalfNaN(bool sign, ulong significand)
{
const uint NaNBits = BiasedExponentMask | 0x200; // Most significant significand bit
uint signInt = (sign ? 1U : 0U) << SignShift;
uint sigInt = (uint)(significand >> 54);
return BitConverter.UInt16BitsToHalf((ushort)(signInt | NaNBits | sigInt));
}
private static ushort RoundPackToHalf(bool sign, short exp, ushort sig)
{
const int RoundIncrement = 0x8; // Depends on rounding mode but it's always towards closest / ties to even
int roundBits = sig & 0xF;
if ((uint)exp >= 0x1D)
{
if (exp < 0)
{
sig = (ushort)ShiftRightJam(sig, -exp);
exp = 0;
roundBits = sig & 0xF;
}
else if (exp > 0x1D || sig + RoundIncrement >= 0x8000) // Overflow
{
return sign ? NegativeInfinityBits : PositiveInfinityBits;
}
}
sig = (ushort)((sig + RoundIncrement) >> 4);
sig &= (ushort)~(((roundBits ^ 8) != 0 ? 0 : 1) & 1);
if (sig == 0)
{
exp = 0;
}
return new Half(sign, (ushort)exp, sig)._value;
}
// If any bits are lost by shifting, "jam" them into the LSB.
// if dist > bit count, Will be 1 or 0 depending on i
// (unlike bitwise operators that masks the lower 5 bits)
private static uint ShiftRightJam(uint i, int dist) => dist < 31 ? (i >> dist) | (i << (-dist & 31) != 0 ? 1U : 0U) : (i != 0 ? 1U : 0U);
private static ulong ShiftRightJam(ulong l, int dist) => dist < 63 ? (l >> dist) | (l << (-dist & 63) != 0 ? 1UL : 0UL) : (l != 0 ? 1UL : 0UL);
private static float CreateSingleNaN(bool sign, ulong significand)
{
const uint NaNBits = float.BiasedExponentMask | 0x400000; // Most significant significand bit
uint signInt = (sign ? 1U : 0U) << float.SignShift;
uint sigInt = (uint)(significand >> 41);
return BitConverter.UInt32BitsToSingle(signInt | NaNBits | sigInt);
}
private static double CreateDoubleNaN(bool sign, ulong significand)
{
const ulong NaNBits = double.BiasedExponentMask | 0x80000_00000000; // Most significant significand bit
ulong signInt = (sign ? 1UL : 0UL) << double.SignShift;
ulong sigInt = significand >> 12;
return BitConverter.UInt64BitsToDouble(signInt | NaNBits | sigInt);
}
private static float CreateSingle(bool sign, byte exp, uint sig) => BitConverter.UInt32BitsToSingle(((sign ? 1U : 0U) << float.SignShift) + ((uint)exp << float.BiasedExponentShift) + sig);
private static double CreateDouble(bool sign, ushort exp, ulong sig) => BitConverter.UInt64BitsToDouble(((sign ? 1UL : 0UL) << double.SignShift) + ((ulong)exp << double.BiasedExponentShift) + sig);
#endregion
//
// IAdditionOperators
//
/// <inheritdoc cref="IAdditionOperators{TSelf, TOther, TResult}.op_Addition(TSelf, TOther)" />
public static Half operator +(Half left, Half right) => (Half)((float)left + (float)right);