Decimal128.cs 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986
  1. /* Copyright 2016 MongoDB Inc.
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. using System;
  16. using System.Collections.Generic;
  17. using System.Globalization;
  18. using System.Text.RegularExpressions;
  19. namespace MongoDB.Bson
  20. {
  21. /// <summary>
  22. /// Represents a Decimal128 value.
  23. /// </summary>
  24. #if NET45
  25. [Serializable]
  26. #endif
  27. public struct Decimal128 : IConvertible, IComparable<Decimal128>, IEquatable<Decimal128>
  28. {
  29. #region static
  30. // private constants
  31. private const short __exponentMax = 6111;
  32. private const short __exponentMin = -6176;
  33. private const short __exponentBias = 6176;
  34. private const short __maxSignificandDigits = 34;
  35. // private static fields
  36. private static readonly UInt128 __maxSignificand = UInt128.Parse("9999999999999999999999999999999999");
  37. private static readonly Decimal128 __maxValue = Decimal128.Parse("9999999999999999999999999999999999E+6111");
  38. private static readonly Decimal128 __minValue = Decimal128.Parse("-9999999999999999999999999999999999E+6111");
  39. // public static properties
  40. /// <summary>
  41. /// Gets the maximum value.
  42. /// </summary>
  43. public static Decimal128 MaxValue =>
  44. __maxValue;
  45. /// <summary>
  46. /// Gets the minimum value.
  47. /// </summary>
  48. public static Decimal128 MinValue =>
  49. __minValue;
  50. /// <summary>
  51. /// Represents negative infinity.
  52. /// </summary>
  53. public static Decimal128 NegativeInfinity =>
  54. new Decimal128(Flags.NegativeInfinity, 0);
  55. /// <summary>
  56. /// Represents one.
  57. /// </summary>
  58. public static Decimal128 One =>
  59. new Decimal128(0, 1);
  60. /// <summary>
  61. /// Represents positive infinity.
  62. /// </summary>
  63. public static Decimal128 PositiveInfinity =>
  64. new Decimal128(Flags.PositiveInfinity, 0);
  65. /// <summary>
  66. /// Represents a value that is not a number.
  67. /// </summary>
  68. public static Decimal128 QNaN =>
  69. new Decimal128(Flags.QNaN, 0);
  70. /// <summary>
  71. /// Represents a value that is not a number and raises errors when used in calculations.
  72. /// </summary>
  73. public static Decimal128 SNaN =>
  74. new Decimal128(Flags.SNaN, 0);
  75. /// <summary>
  76. /// Represents zero.
  77. /// </summary>
  78. public static Decimal128 Zero =>
  79. new Decimal128(0, 0);
  80. // public static operators
  81. /// <summary>
  82. /// Implements the operator ==.
  83. /// </summary>
  84. /// <param name="lhs">The LHS.</param>
  85. /// <param name="rhs">The RHS.</param>
  86. /// <returns>
  87. /// The result of the operator.
  88. /// </returns>
  89. public static bool operator ==(Decimal128 lhs, Decimal128 rhs)
  90. {
  91. if (Decimal128.IsNaN(lhs) || Decimal128.IsNaN(rhs))
  92. {
  93. return false;
  94. }
  95. else
  96. {
  97. return lhs.Equals(rhs);
  98. }
  99. }
  100. /// <summary>
  101. /// Implements the operator !=.
  102. /// </summary>
  103. /// <param name="lhs">The LHS.</param>
  104. /// <param name="rhs">The RHS.</param>
  105. /// <returns>
  106. /// The result of the operator.
  107. /// </returns>
  108. public static bool operator !=(Decimal128 lhs, Decimal128 rhs)
  109. {
  110. return !(lhs == rhs);
  111. }
  112. /// <summary>
  113. /// Returns a value indicating whether a specified Decimal128 is greater than another specified Decimal128.
  114. /// </summary>
  115. /// <param name="x">The first value.</param>
  116. /// <param name="y">The second value.</param>
  117. /// <returns>
  118. /// true if x &gt; y; otherwise, false.
  119. /// </returns>
  120. public static bool operator >(Decimal128 x, Decimal128 y)
  121. {
  122. return Decimal128.Compare(x, y) > 0;
  123. }
  124. /// <summary>
  125. /// Returns a value indicating whether a specified Decimal128 is greater than or equal to another another specified Decimal128.
  126. /// </summary>
  127. /// <param name="x">The first value.</param>
  128. /// <param name="y">The second value.</param>
  129. /// <returns>
  130. /// true if x &gt;= y; otherwise, false.
  131. /// </returns>
  132. public static bool operator >=(Decimal128 x, Decimal128 y)
  133. {
  134. return Decimal128.Compare(x, y) >= 0;
  135. }
  136. /// <summary>
  137. /// Returns a value indicating whether a specified Decimal128 is less than another specified Decimal128.
  138. /// </summary>
  139. /// <param name="x">The first value.</param>
  140. /// <param name="y">The second value.</param>
  141. /// <returns>
  142. /// true if x &lt; y; otherwise, false.
  143. /// </returns>
  144. public static bool operator <(Decimal128 x, Decimal128 y)
  145. {
  146. return Decimal128.Compare(x, y) < 0;
  147. }
  148. /// <summary>
  149. /// Returns a value indicating whether a specified Decimal128 is less than or equal to another another specified Decimal128.
  150. /// </summary>
  151. /// <param name="x">The first value.</param>
  152. /// <param name="y">The second value.</param>
  153. /// <returns>
  154. /// true if x &lt;= y; otherwise, false.
  155. /// </returns>
  156. public static bool operator <=(Decimal128 x, Decimal128 y)
  157. {
  158. return Decimal128.Compare(x, y) <= 0;
  159. }
  160. /// <summary>
  161. /// Performs an explicit conversion from <see cref="Decimal128"/> to <see cref="System.Byte"/>.
  162. /// </summary>
  163. /// <param name="value">The value to convert.</param>
  164. /// <returns>
  165. /// The result of the conversion.
  166. /// </returns>
  167. public static explicit operator byte(Decimal128 value)
  168. {
  169. return ToByte(value);
  170. }
  171. /// <summary>
  172. /// Performs an explicit conversion from <see cref="Decimal128"/> to <see cref="char"/>.
  173. /// </summary>
  174. /// <param name="value">The value to convert.</param>
  175. /// <returns>
  176. /// The result of the conversion.
  177. /// </returns>
  178. public static explicit operator char(Decimal128 value)
  179. {
  180. return (char)ToUInt16(value);
  181. }
  182. /// <summary>
  183. /// Performs an explicit conversion from <see cref="Decimal128"/> to <see cref="System.Decimal"/>.
  184. /// </summary>
  185. /// <param name="value">The value to convert.</param>
  186. /// <returns>
  187. /// The result of the conversion.
  188. /// </returns>
  189. public static explicit operator decimal(Decimal128 value)
  190. {
  191. return ToDecimal(value);
  192. }
  193. /// <summary>
  194. /// Performs an implicit conversion from <see cref="System.Byte"/> to <see cref="Decimal128"/>.
  195. /// </summary>
  196. /// <param name="value">The value.</param>
  197. /// <returns>
  198. /// The result of the conversion.
  199. /// </returns>
  200. public static implicit operator Decimal128(byte value)
  201. {
  202. return new Decimal128(value);
  203. }
  204. /// <summary>
  205. /// Performs an implicit conversion from <see cref="System.Decimal"/> to <see cref="Decimal128"/>.
  206. /// </summary>
  207. /// <param name="value">The value.</param>
  208. /// <returns>
  209. /// The result of the conversion.
  210. /// </returns>
  211. public static implicit operator Decimal128(decimal value)
  212. {
  213. return new Decimal128(value);
  214. }
  215. /// <summary>
  216. /// Performs an explicit conversion from <see cref="double"/> to <see cref="Decimal128"/>.
  217. /// </summary>
  218. /// <param name="value">The value.</param>
  219. /// <returns>
  220. /// The result of the conversion.
  221. /// </returns>
  222. public static explicit operator Decimal128(double value)
  223. {
  224. return new Decimal128(value);
  225. }
  226. /// <summary>
  227. /// Performs an explicit conversion from <see cref="float"/> to <see cref="Decimal128"/>.
  228. /// </summary>
  229. /// <param name="value">The value.</param>
  230. /// <returns>
  231. /// The result of the conversion.
  232. /// </returns>
  233. public static explicit operator Decimal128(float value)
  234. {
  235. return new Decimal128(value);
  236. }
  237. /// <summary>
  238. /// Performs an implicit conversion from <see cref="System.Int32"/> to <see cref="Decimal128"/>.
  239. /// </summary>
  240. /// <param name="value">The value.</param>
  241. /// <returns>
  242. /// The result of the conversion.
  243. /// </returns>
  244. public static implicit operator Decimal128(int value)
  245. {
  246. return new Decimal128(value);
  247. }
  248. /// <summary>
  249. /// Performs an implicit conversion from <see cref="System.Int64"/> to <see cref="Decimal128"/>.
  250. /// </summary>
  251. /// <param name="value">The value.</param>
  252. /// <returns>
  253. /// The result of the conversion.
  254. /// </returns>
  255. public static implicit operator Decimal128(long value)
  256. {
  257. return new Decimal128(value);
  258. }
  259. /// <summary>
  260. /// Performs an implicit conversion from <see cref="System.SByte"/> to <see cref="Decimal128"/>.
  261. /// </summary>
  262. /// <param name="value">The value.</param>
  263. /// <returns>
  264. /// The result of the conversion.
  265. /// </returns>
  266. [CLSCompliant(false)]
  267. public static implicit operator Decimal128(sbyte value)
  268. {
  269. return new Decimal128(value);
  270. }
  271. /// <summary>
  272. /// Performs an implicit conversion from <see cref="System.Int16"/> to <see cref="Decimal128"/>.
  273. /// </summary>
  274. /// <param name="value">The value.</param>
  275. /// <returns>
  276. /// The result of the conversion.
  277. /// </returns>
  278. public static implicit operator Decimal128(short value)
  279. {
  280. return new Decimal128(value);
  281. }
  282. /// <summary>
  283. /// Performs an implicit conversion from <see cref="System.UInt32"/> to <see cref="Decimal128"/>.
  284. /// </summary>
  285. /// <param name="value">The value.</param>
  286. /// <returns>
  287. /// The result of the conversion.
  288. /// </returns>
  289. [CLSCompliant(false)]
  290. public static implicit operator Decimal128(uint value)
  291. {
  292. return new Decimal128(value);
  293. }
  294. /// <summary>
  295. /// Performs an implicit conversion from <see cref="System.UInt16"/> to <see cref="Decimal128"/>.
  296. /// </summary>
  297. /// <param name="value">The value.</param>
  298. /// <returns>
  299. /// The result of the conversion.
  300. /// </returns>
  301. [CLSCompliant(false)]
  302. public static implicit operator Decimal128(ushort value)
  303. {
  304. return new Decimal128(value);
  305. }
  306. /// <summary>
  307. /// Performs an implicit conversion from <see cref="System.UInt64"/> to <see cref="Decimal128"/>.
  308. /// </summary>
  309. /// <param name="value">The value.</param>
  310. /// <returns>
  311. /// The result of the conversion.
  312. /// </returns>
  313. [CLSCompliant(false)]
  314. public static implicit operator Decimal128(ulong value)
  315. {
  316. return new Decimal128(value);
  317. }
  318. /// <summary>
  319. /// Performs an explicit conversion from <see cref="Decimal128"/> to <see cref="double"/>.
  320. /// </summary>
  321. /// <param name="value">The value to convert.</param>
  322. /// <returns>
  323. /// The result of the conversion.
  324. /// </returns>
  325. public static explicit operator double(Decimal128 value)
  326. {
  327. return Decimal128.ToDouble(value);
  328. }
  329. /// <summary>
  330. /// Performs an explicit conversion from <see cref="Decimal128"/> to <see cref="float"/>.
  331. /// </summary>
  332. /// <param name="value">The value to convert.</param>
  333. /// <returns>
  334. /// The result of the conversion.
  335. /// </returns>
  336. public static explicit operator float(Decimal128 value)
  337. {
  338. return Decimal128.ToSingle(value);
  339. }
  340. /// <summary>
  341. /// Performs an explicit conversion from <see cref="Decimal128"/> to <see cref="System.Int32"/>.
  342. /// </summary>
  343. /// <param name="value">The value to convert.</param>
  344. /// <returns>
  345. /// The result of the conversion.
  346. /// </returns>
  347. public static explicit operator int(Decimal128 value)
  348. {
  349. return ToInt32(value);
  350. }
  351. /// <summary>
  352. /// Performs an explicit conversion from <see cref="Decimal128"/> to <see cref="System.Int64"/>.
  353. /// </summary>
  354. /// <param name="value">The value to convert.</param>
  355. /// <returns>
  356. /// The result of the conversion.
  357. /// </returns>
  358. public static explicit operator long(Decimal128 value)
  359. {
  360. return ToInt64(value);
  361. }
  362. /// <summary>
  363. /// Performs an explicit conversion from <see cref="Decimal128"/> to <see cref="System.SByte"/>.
  364. /// </summary>
  365. /// <param name="value">The value to convert.</param>
  366. /// <returns>
  367. /// The result of the conversion.
  368. /// </returns>
  369. [CLSCompliant(false)]
  370. public static explicit operator sbyte(Decimal128 value)
  371. {
  372. return ToSByte(value);
  373. }
  374. /// <summary>
  375. /// Performs an explicit conversion from <see cref="Decimal128"/> to <see cref="System.Int16"/>.
  376. /// </summary>
  377. /// <param name="value">The value to convert.</param>
  378. /// <returns>
  379. /// The result of the conversion.
  380. /// </returns>
  381. public static explicit operator short(Decimal128 value)
  382. {
  383. return ToInt16(value);
  384. }
  385. /// <summary>
  386. /// Performs an explicit conversion from <see cref="Decimal128"/> to <see cref="System.UInt32"/>.
  387. /// </summary>
  388. /// <param name="value">The value to convert.</param>
  389. /// <returns>
  390. /// The result of the conversion.
  391. /// </returns>
  392. [CLSCompliant(false)]
  393. public static explicit operator uint(Decimal128 value)
  394. {
  395. return ToUInt32(value);
  396. }
  397. /// <summary>
  398. /// Performs an explicit conversion from <see cref="Decimal128"/> to <see cref="System.UInt64"/>.
  399. /// </summary>
  400. /// <param name="value">The value to convert.</param>
  401. /// <returns>
  402. /// The result of the conversion.
  403. /// </returns>
  404. [CLSCompliant(false)]
  405. public static explicit operator ulong(Decimal128 value)
  406. {
  407. return ToUInt64(value);
  408. }
  409. /// <summary>
  410. /// Performs an explicit conversion from <see cref="Decimal128"/> to <see cref="System.UInt16"/>.
  411. /// </summary>
  412. /// <param name="value">The value to convert.</param>
  413. /// <returns>
  414. /// The result of the conversion.
  415. /// </returns>
  416. [CLSCompliant(false)]
  417. public static explicit operator ushort(Decimal128 value)
  418. {
  419. return ToUInt16(value);
  420. }
  421. // public static methods
  422. /// <summary>
  423. /// Compares two specified Decimal128 values and returns an integer that indicates whether the first value
  424. /// is greater than, less than, or equal to the second value.
  425. /// </summary>
  426. /// <param name="x">The first value.</param>
  427. /// <param name="y">The second value.</param>
  428. /// <returns>Less than zero if x &lt; y, zero if x == y, and greater than zero if x &gt; y.</returns>
  429. public static int Compare(Decimal128 x, Decimal128 y)
  430. {
  431. return Decimal128Comparer.Instance.Compare(x, y);
  432. }
  433. /// <summary>
  434. /// Determines whether the specified Decimal128 instances are considered equal.
  435. /// </summary>
  436. /// <param name="x">The first Decimal128 object to compare.</param>
  437. /// <param name="y">The second Decimal128 object to compare.</param>
  438. /// <returns>True if the objects are considered equal; otherwise false. If both x and y are null, the method returns true.</returns>
  439. public static bool Equals(Decimal128 x, Decimal128 y)
  440. {
  441. return Decimal128.Compare(x, y) == 0;
  442. }
  443. /// <summary>
  444. /// Creates a new Decimal128 value from its components.
  445. /// </summary>
  446. /// <param name="isNegative">if set to <c>true</c> [is negative].</param>
  447. /// <param name="exponent">The exponent.</param>
  448. /// <param name="significandHighBits">The signficand high bits.</param>
  449. /// <param name="significandLowBits">The significand low bits.</param>
  450. /// <returns>A Decimal128 value.</returns>
  451. [CLSCompliant(false)]
  452. public static Decimal128 FromComponents(bool isNegative, short exponent, ulong significandHighBits, ulong significandLowBits)
  453. {
  454. return FromComponents(isNegative, exponent, new UInt128(significandHighBits, significandLowBits));
  455. }
  456. /// <summary>
  457. /// Creates a new Decimal128 value from the IEEE encoding bits.
  458. /// </summary>
  459. /// <param name="highBits">The high bits.</param>
  460. /// <param name="lowBits">The low bits.</param>
  461. /// <returns>A Decimal128 value.</returns>
  462. [CLSCompliant(false)]
  463. public static Decimal128 FromIEEEBits(ulong highBits, ulong lowBits)
  464. {
  465. return new Decimal128(MapIEEEHighBitsToDecimal128HighBits(highBits), lowBits);
  466. }
  467. /// <summary>
  468. /// Gets the exponent of a Decimal128 value.
  469. /// </summary>
  470. /// <param name="d">The Decimal128 value.</param>
  471. /// <returns>The exponent.</returns>
  472. public static short GetExponent(Decimal128 d)
  473. {
  474. if (Flags.IsFirstForm(d._highBits))
  475. {
  476. return MapDecimal128BiasedExponentToExponent((short)((d._highBits & Flags.FirstFormExponentBits) >> 49));
  477. }
  478. else if (Flags.IsSecondForm(d._highBits))
  479. {
  480. return MapDecimal128BiasedExponentToExponent((short)((d._highBits & Flags.SecondFormExponentBits) >> 47));
  481. }
  482. else
  483. {
  484. throw new InvalidOperationException("GetExponent cannot be called for Infinity or NaN.");
  485. }
  486. }
  487. /// <summary>
  488. /// Gets the high bits of the significand of a Decimal128 value.
  489. /// </summary>
  490. /// <param name="d">The Decimal128 value.</param>
  491. /// <returns>The high bits of the significand.</returns>
  492. [CLSCompliant(false)]
  493. public static ulong GetSignificandHighBits(Decimal128 d)
  494. {
  495. if (Flags.IsFirstForm(d._highBits))
  496. {
  497. return d._highBits & Flags.FirstFormSignificandBits;
  498. }
  499. else if (Flags.IsSecondForm(d._highBits))
  500. {
  501. return 0;
  502. }
  503. else
  504. {
  505. throw new InvalidOperationException("GetSignificandHighBits cannot be called for Infinity or NaN.");
  506. }
  507. }
  508. /// <summary>
  509. /// Gets the high bits of the significand of a Decimal128 value.
  510. /// </summary>
  511. /// <param name="d">The Decimal128 value.</param>
  512. /// <returns>The high bits of the significand.</returns>
  513. [CLSCompliant(false)]
  514. public static ulong GetSignificandLowBits(Decimal128 d)
  515. {
  516. if (Flags.IsFirstForm(d._highBits))
  517. {
  518. return d._lowBits;
  519. }
  520. else if (Flags.IsSecondForm(d._highBits))
  521. {
  522. return 0;
  523. }
  524. else
  525. {
  526. throw new InvalidOperationException("GetSignificandLowBits cannot be called for Infinity or NaN.");
  527. }
  528. }
  529. /// <summary>
  530. /// Returns a value indicating whether the specified number evaluates to negative or positive infinity.
  531. /// </summary>
  532. /// <param name="d">A 128-bit decimal.</param>
  533. /// <returns>true if <paramref name="d" /> evaluates to negative or positive infinity; otherwise, false.</returns>
  534. public static bool IsInfinity(Decimal128 d) => Flags.IsInfinity(d._highBits);
  535. /// <summary>
  536. /// Returns a value indicating whether the specified number is not a number.
  537. /// </summary>
  538. /// <param name="d">A 128-bit decimal.</param>
  539. /// <returns>true if <paramref name="d" /> is not a number; otherwise, false.</returns>
  540. public static bool IsNaN(Decimal128 d) => Flags.IsNaN(d._highBits);
  541. /// <summary>
  542. /// Returns a value indicating whether the specified number is negative.
  543. /// </summary>
  544. /// <param name="d">A 128-bit decimal.</param>
  545. /// <returns>true if <paramref name="d" /> is negative; otherwise, false.</returns>
  546. public static bool IsNegative(Decimal128 d) => Flags.IsNegative(d._highBits);
  547. /// <summary>
  548. /// Returns a value indicating whether the specified number evaluates to negative infinity.
  549. /// </summary>
  550. /// <param name="d">A 128-bit decimal.</param>
  551. /// <returns>true if <paramref name="d" /> evaluates to negative infinity; otherwise, false.</returns>
  552. public static bool IsNegativeInfinity(Decimal128 d) => Flags.IsNegativeInfinity(d._highBits);
  553. /// <summary>
  554. /// Returns a value indicating whether the specified number evaluates to positive infinity.
  555. /// </summary>
  556. /// <param name="d">A 128-bit decimal.</param>
  557. /// <returns>true if <paramref name="d" /> evaluates to positive infinity; otherwise, false.</returns>
  558. public static bool IsPositiveInfinity(Decimal128 d) => Flags.IsPositiveInfinity(d._highBits);
  559. /// <summary>
  560. /// Returns a value indicating whether the specified number is a quiet not a number.
  561. /// </summary>
  562. /// <param name="d">A 128-bit decimal.</param>
  563. /// <returns>true if <paramref name="d" /> is a quiet not a number; otherwise, false.</returns>
  564. public static bool IsQNaN(Decimal128 d) => Flags.IsQNaN(d._highBits);
  565. /// <summary>
  566. /// Returns a value indicating whether the specified number is a signaled not a number.
  567. /// </summary>
  568. /// <param name="d">A 128-bit decimal.</param>
  569. /// <returns>true if <paramref name="d" /> is a signaled not a number; otherwise, false.</returns>
  570. public static bool IsSNaN(Decimal128 d) => Flags.IsSNaN(d._highBits);
  571. /// <summary>
  572. /// Gets a value indicating whether this instance is zero.
  573. /// </summary>
  574. /// <value>
  575. /// <c>true</c> if this instance is zero; otherwise, <c>false</c>.
  576. /// </value>
  577. public static bool IsZero(Decimal128 d)
  578. {
  579. if (Flags.IsFirstForm(d._highBits) && GetSignificand(d).Equals(UInt128.Zero))
  580. {
  581. return true;
  582. }
  583. else if (Flags.IsSecondForm(d._highBits))
  584. {
  585. // all second form values are invalid representations and are interpreted as zero
  586. return true;
  587. }
  588. else
  589. {
  590. return false;
  591. }
  592. }
  593. /// <summary>
  594. /// Negates the specified x.
  595. /// </summary>
  596. /// <param name="x">The x.</param>
  597. /// <returns>The result of multiplying the value by negative one.</returns>
  598. public static Decimal128 Negate(Decimal128 x)
  599. {
  600. return new Decimal128(x._highBits ^ Flags.SignBit, x._lowBits);
  601. }
  602. /// <summary>
  603. /// Converts the string representation of a number to its <see cref="Decimal128" /> equivalent.
  604. /// </summary>
  605. /// <param name="s">The string representation of the number to convert.</param>
  606. /// <returns>
  607. /// The equivalent to the number contained in <paramref name="s" />.
  608. /// </returns>
  609. public static Decimal128 Parse(string s)
  610. {
  611. Decimal128 value;
  612. if (!TryParse(s, out value))
  613. {
  614. throw new FormatException($"{s} is not a valid Decimal128.");
  615. }
  616. return value;
  617. }
  618. /// <summary>
  619. /// Converts the value of the specified <see cref="Decimal128"/> to the equivalent 8-bit unsigned integer.
  620. /// </summary>
  621. /// <param name="d">The number to convert.</param>
  622. /// <returns>A 8-bit unsigned integer equivalent to <paramref name="d" />.</returns>
  623. public static byte ToByte(Decimal128 d)
  624. {
  625. if (Flags.IsFirstForm(d._highBits))
  626. {
  627. ulong value;
  628. if (Decimal128.TryTruncateToUInt64(d, 0, byte.MaxValue, out value))
  629. {
  630. return (byte)value;
  631. }
  632. else
  633. {
  634. throw new OverflowException("Value is too large or too small to be converted to a Byte.");
  635. }
  636. }
  637. else if (Flags.IsSecondForm(d._highBits))
  638. {
  639. return 0;
  640. }
  641. else
  642. {
  643. throw new OverflowException("Infinity or NaN cannot be converted to a Byte.");
  644. }
  645. }
  646. /// <summary>
  647. /// Converts the value of the specified <see cref="Decimal128"/> to the equivalent <see cref="decimal"/>.
  648. /// </summary>
  649. /// <param name="d">The number to convert.</param>
  650. /// <returns>A <see cref="decimal"/> equivalent to <paramref name="d" />.</returns>
  651. public static decimal ToDecimal(Decimal128 d)
  652. {
  653. if (Flags.IsFirstForm(d._highBits))
  654. {
  655. var exponent = Decimal128.GetExponent(d);
  656. // try to get the exponent within the range of 0 to -28
  657. if (exponent > 0)
  658. {
  659. d = Decimal128.DecreaseExponent(d, 0);
  660. exponent = Decimal128.GetExponent(d);
  661. }
  662. else if (exponent < -28)
  663. {
  664. d = Decimal128.IncreaseExponent(d, -28);
  665. exponent = Decimal128.GetExponent(d);
  666. }
  667. // try to get the significand to have zeros for the high order 32 bits
  668. var significand = Decimal128.GetSignificand(d);
  669. while ((significand.High >> 32) != 0)
  670. {
  671. uint remainder;
  672. var significandDividedBy10 = UInt128.Divide(significand, (uint)10, out remainder);
  673. if (remainder != 0)
  674. {
  675. break;
  676. }
  677. exponent += 1;
  678. significand = significandDividedBy10;
  679. }
  680. if (exponent < -28 || exponent > 0 || (significand.High >> 32) != 0)
  681. {
  682. throw new OverflowException("Value is too large or too small to be converted to a Decimal.");
  683. }
  684. var lo = (int)significand.Low;
  685. var mid = (int)(significand.Low >> 32);
  686. var hi = (int)significand.High;
  687. var isNegative = Decimal128.IsNegative(d);
  688. var scale = (byte)(-exponent);
  689. return new decimal(lo, mid, hi, isNegative, scale);
  690. }
  691. else if (Flags.IsSecondForm(d._highBits))
  692. {
  693. return Decimal.Zero;
  694. }
  695. else
  696. {
  697. throw new OverflowException("Infinity or NaN cannot be converted to Decimal.");
  698. }
  699. }
  700. /// <summary>
  701. /// Converts the value of the specified <see cref="Decimal128"/> to the equivalent <see cref="double"/>.
  702. /// </summary>
  703. /// <param name="d">The number to convert.</param>
  704. /// <returns>A <see cref="double"/> equivalent to <paramref name="d" />.</returns>
  705. public static double ToDouble(Decimal128 d)
  706. {
  707. if (Flags.IsFirstForm(d._highBits))
  708. {
  709. // TODO: implement this more efficiently
  710. var stringValue = d.ToString();
  711. return double.Parse(stringValue);
  712. }
  713. else if (Flags.IsSecondForm(d._highBits))
  714. {
  715. return 0.0;
  716. }
  717. else if (Flags.IsPositiveInfinity(d._highBits))
  718. {
  719. return double.PositiveInfinity;
  720. }
  721. else if (Flags.IsNegativeInfinity(d._highBits))
  722. {
  723. return double.NegativeInfinity;
  724. }
  725. else
  726. {
  727. return double.NaN;
  728. }
  729. }
  730. /// <summary>
  731. /// Converts the value of the specified <see cref="Decimal128"/> to the equivalent 16-bit signed integer.
  732. /// </summary>
  733. /// <param name="d">The number to convert.</param>
  734. /// <returns>A 16-bit signed integer equivalent to <paramref name="d" />.</returns>
  735. public static short ToInt16(Decimal128 d)
  736. {
  737. if (Flags.IsFirstForm(d._highBits))
  738. {
  739. var maxNegativeValue = (ulong)short.MaxValue + 1;
  740. ulong value;
  741. if (Decimal128.TryTruncateToUInt64(d, maxNegativeValue, (ulong)short.MaxValue, out value))
  742. {
  743. return Decimal128.IsNegative(d) ? (value == maxNegativeValue ? short.MinValue : (short )(-(short)value)) : (short)value;
  744. }
  745. else
  746. {
  747. throw new OverflowException("Value is too large or too small to be converted to an Int16.");
  748. }
  749. }
  750. else if (Flags.IsSecondForm(d._highBits))
  751. {
  752. return 0;
  753. }
  754. else
  755. {
  756. throw new OverflowException("Infinity or NaN cannot be converted to an Int16.");
  757. }
  758. }
  759. /// <summary>
  760. /// Converts the value of the specified <see cref="Decimal128"/> to the equivalent 32-bit signed integer.
  761. /// </summary>
  762. /// <param name="d">The number to convert.</param>
  763. /// <returns>A 32-bit signed integer equivalent to <paramref name="d" />.</returns>
  764. public static int ToInt32(Decimal128 d)
  765. {
  766. if (Flags.IsFirstForm(d._highBits))
  767. {
  768. var maxNegativeValue = (ulong)int.MaxValue + 1;
  769. ulong value;
  770. if (Decimal128.TryTruncateToUInt64(d, maxNegativeValue, int.MaxValue, out value))
  771. {
  772. return Decimal128.IsNegative(d) ? (value == maxNegativeValue ? int.MinValue : -(int)value) : (int)value;
  773. }
  774. else
  775. {
  776. throw new OverflowException("Value is too large or too small to be converted to an Int32.");
  777. }
  778. }
  779. else if (Flags.IsSecondForm(d._highBits))
  780. {
  781. return 0;
  782. }
  783. else
  784. {
  785. throw new OverflowException("Infinity or NaN cannot be converted to an Int32.");
  786. }
  787. }
  788. /// <summary>
  789. /// Converts the value of the specified <see cref="Decimal128"/> to the equivalent 64-bit signed integer.
  790. /// </summary>
  791. /// <param name="d">The number to convert.</param>
  792. /// <returns>A 64-bit signed integer equivalent to <paramref name="d" />.</returns>
  793. public static long ToInt64(Decimal128 d)
  794. {
  795. if (Flags.IsFirstForm(d._highBits))
  796. {
  797. ulong maxNegativeValue = (ulong)long.MaxValue + 1;
  798. ulong value;
  799. if (Decimal128.TryTruncateToUInt64(d, maxNegativeValue, long.MaxValue, out value))
  800. {
  801. return Decimal128.IsNegative(d) ? (value == maxNegativeValue ? long.MinValue : -(long)value) : (long)value;
  802. }
  803. else
  804. {
  805. throw new OverflowException("Value is too large or too small to be converted to an Int64.");
  806. }
  807. }
  808. else if (Flags.IsSecondForm(d._highBits))
  809. {
  810. return 0;
  811. }
  812. else
  813. {
  814. throw new OverflowException("Infinity or NaN cannot be converted to an Int64.");
  815. }
  816. }
  817. /// <summary>
  818. /// Converts the value of the specified <see cref="Decimal128"/> to the equivalent 8-bit signed integer.
  819. /// </summary>
  820. /// <param name="d">The number to convert.</param>
  821. /// <returns>A 8-bit signed integer equivalent to <paramref name="d" />.</returns>
  822. [CLSCompliant(false)]
  823. public static sbyte ToSByte(Decimal128 d)
  824. {
  825. if (Flags.IsFirstForm(d._highBits))
  826. {
  827. ulong maxNegativeValue = (ulong)sbyte.MaxValue + 1;
  828. ulong value;
  829. if (Decimal128.TryTruncateToUInt64(d, maxNegativeValue, (ulong)sbyte.MaxValue, out value))
  830. {
  831. return Decimal128.IsNegative(d) ? (value == maxNegativeValue ? sbyte.MinValue : (sbyte)(-(sbyte)value)) : (sbyte)value;
  832. }
  833. else
  834. {
  835. throw new OverflowException("Value is too large or too small to be converted to an SByte.");
  836. }
  837. }
  838. else if (Flags.IsSecondForm(d._highBits))
  839. {
  840. return 0;
  841. }
  842. else
  843. {
  844. throw new OverflowException("Infinity or NaN cannot be converted to an SByte.");
  845. }
  846. }
  847. /// <summary>
  848. /// Converts the value of the specified <see cref="Decimal128"/> to the equivalent <see cref="float"/>.
  849. /// </summary>
  850. /// <param name="d">The number to convert.</param>
  851. /// <returns>A <see cref="float"/> equivalent to <paramref name="d" />.</returns>
  852. public static float ToSingle(Decimal128 d)
  853. {
  854. if (Flags.IsFirstForm(d._highBits))
  855. {
  856. // TODO: implement this more efficiently
  857. var stringValue = d.ToString();
  858. return float.Parse(stringValue);
  859. }
  860. else if (Flags.IsSecondForm(d._highBits))
  861. {
  862. return (float)0.0;
  863. }
  864. else if (Flags.IsPositiveInfinity(d._highBits))
  865. {
  866. return float.PositiveInfinity;
  867. }
  868. else if (Flags.IsNegativeInfinity(d._highBits))
  869. {
  870. return float.NegativeInfinity;
  871. }
  872. else
  873. {
  874. return float.NaN;
  875. }
  876. }
  877. /// <summary>
  878. /// Converts the value of the specified <see cref="Decimal128"/> to the equivalent 16-bit unsigned integer.
  879. /// </summary>
  880. /// <param name="d">The number to convert.</param>
  881. /// <returns>A 16-bit unsigned integer equivalent to <paramref name="d" />.</returns>
  882. [CLSCompliant(false)]
  883. public static ushort ToUInt16(Decimal128 d)
  884. {
  885. if (Flags.IsFirstForm(d._highBits))
  886. {
  887. ulong value;
  888. if (Decimal128.TryTruncateToUInt64(d, 0, ushort.MaxValue, out value))
  889. {
  890. return (ushort)value;
  891. }
  892. else
  893. {
  894. throw new OverflowException("Value is too large or too small to be converted to a UInt16.");
  895. }
  896. }
  897. else if (Flags.IsSecondForm(d._highBits))
  898. {
  899. return 0;
  900. }
  901. else
  902. {
  903. throw new OverflowException("Infinity or NaN cannot be converted to a UInt16.");
  904. }
  905. }
  906. /// <summary>
  907. /// Converts the value of the specified <see cref="Decimal128"/> to the equivalent 32-bit unsigned integer.
  908. /// </summary>
  909. /// <param name="d">The number to convert.</param>
  910. /// <returns>A 32-bit unsigned integer equivalent to <paramref name="d" />.</returns>
  911. [CLSCompliant(false)]
  912. public static uint ToUInt32(Decimal128 d)
  913. {
  914. if (Flags.IsFirstForm(d._highBits))
  915. {
  916. ulong value;
  917. if (Decimal128.TryTruncateToUInt64(d, 0, uint.MaxValue, out value))
  918. {
  919. return (uint)value;
  920. }
  921. else
  922. {
  923. throw new OverflowException("Value is too large or too small to be converted to a UInt32.");
  924. }
  925. }
  926. else if (Flags.IsSecondForm(d._highBits))
  927. {
  928. return 0;
  929. }
  930. else
  931. {
  932. throw new OverflowException("Infinity or NaN cannot be converted to a UInt32.");
  933. }
  934. }
  935. /// <summary>
  936. /// Converts the value of the specified <see cref="Decimal128"/> to the equivalent 64-bit unsigned integer.
  937. /// </summary>
  938. /// <param name="d">The number to convert.</param>
  939. /// <returns>A 64-bit unsigned integer equivalent to <paramref name="d" />.</returns>
  940. [CLSCompliant(false)]
  941. public static ulong ToUInt64(Decimal128 d)
  942. {
  943. if (Flags.IsFirstForm(d._highBits))
  944. {
  945. ulong value;
  946. if (Decimal128.TryTruncateToUInt64(d, 0, ulong.MaxValue, out value))
  947. {
  948. return value;
  949. }
  950. else
  951. {
  952. throw new OverflowException("Value is too large or too small to be converted to a UInt64.");
  953. }
  954. }
  955. else if (Flags.IsSecondForm(d._highBits))
  956. {
  957. return 0;
  958. }
  959. else
  960. {
  961. throw new OverflowException("Infinity or NaN cannot be converted to a UInt64.");
  962. }
  963. }
  964. /// <summary>
  965. /// Converts the string representation of a number to its <see cref="Decimal128" /> equivalent. A return value indicates whether the conversion succeeded or failed.
  966. /// </summary>
  967. /// <param name="s">The string representation of the number to convert.</param>
  968. /// <param name="result">When this method returns, contains the <see cref="Decimal128" /> number that is equivalent to the numeric value contained in <paramref name="s" />, if the conversion succeeded, or is zero if the conversion failed. The conversion fails if the <paramref name="s" /> parameter is null, is not a number in a valid format, or represents a number less than the min value or greater than the max value. This parameter is passed uninitialized.</param>
  969. /// <returns>
  970. /// true if <paramref name="s" /> was converted successfully; otherwise, false.
  971. /// </returns>
  972. public static bool TryParse(string s, out Decimal128 result)
  973. {
  974. if (s == null || s.Length == 0)
  975. {
  976. result = default(Decimal128);
  977. return false;
  978. }
  979. const string pattern =
  980. @"^(?<sign>[+-])?" +
  981. @"(?<significand>\d+([.]\d*)?|[.]\d+)" +
  982. @"(?<exponent>[eE](?<exponentSign>[+-])?(?<exponentDigits>\d+))?$";
  983. var match = Regex.Match(s, pattern);
  984. if (!match.Success)
  985. {
  986. if (s.Equals("Inf", StringComparison.OrdinalIgnoreCase) || s.Equals("Infinity", StringComparison.OrdinalIgnoreCase) ||
  987. s.Equals("+Inf", StringComparison.OrdinalIgnoreCase) || s.Equals("+Infinity", StringComparison.OrdinalIgnoreCase))
  988. {
  989. result = Decimal128.PositiveInfinity;
  990. return true;
  991. }
  992. if (s.Equals("-Inf", StringComparison.OrdinalIgnoreCase) || s.Equals("-Infinity", StringComparison.OrdinalIgnoreCase))
  993. {
  994. result = Decimal128.NegativeInfinity;
  995. return true;
  996. }
  997. if (s.Equals("NaN", StringComparison.OrdinalIgnoreCase) || s.Equals("-NaN", StringComparison.OrdinalIgnoreCase))
  998. {
  999. result = Decimal128.QNaN;
  1000. return true;
  1001. }
  1002. result = default(Decimal128);
  1003. return false;
  1004. }
  1005. var isNegative = match.Groups["sign"].Value == "-";
  1006. var exponent = 0;
  1007. if (match.Groups["exponent"].Length != 0)
  1008. {
  1009. if (!int.TryParse(match.Groups["exponentDigits"].Value, out exponent))
  1010. {
  1011. result = default(Decimal128);
  1012. return false;
  1013. }
  1014. if (match.Groups["exponentSign"].Value == "-")
  1015. {
  1016. exponent = -exponent;
  1017. }
  1018. }
  1019. var significandString = match.Groups["significand"].Value;
  1020. int decimalPointIndex;
  1021. if ((decimalPointIndex = significandString.IndexOf('.')) != -1)
  1022. {
  1023. exponent -= significandString.Length - (decimalPointIndex + 1);
  1024. significandString = significandString.Substring(0, decimalPointIndex) + significandString.Substring(decimalPointIndex + 1);
  1025. }
  1026. significandString = RemoveLeadingZeroes(significandString);
  1027. significandString = ClampOrRound(ref exponent, significandString);
  1028. if (exponent > __exponentMax || exponent < __exponentMin)
  1029. {
  1030. result = default(Decimal128);
  1031. return false;
  1032. }
  1033. if (significandString.Length > 34)
  1034. {
  1035. result = default(Decimal128);
  1036. return false;
  1037. }
  1038. var significand = UInt128.Parse(significandString);
  1039. result = Decimal128.FromComponents(isNegative, (short)exponent, significand);
  1040. return true;
  1041. }
  1042. // private static methods
  1043. private static string ClampOrRound(ref int exponent, string significandString)
  1044. {
  1045. if (exponent > __exponentMax)
  1046. {
  1047. if (significandString == "0")
  1048. {
  1049. // since significand is zero simply use the largest possible exponent
  1050. exponent = __exponentMax;
  1051. }
  1052. else
  1053. {
  1054. // use clamping to bring the exponent into range
  1055. var numberOfTrailingZeroesToAdd = exponent - __exponentMax;
  1056. var digitsAvailable = 34 - significandString.Length;
  1057. if (numberOfTrailingZeroesToAdd <= digitsAvailable)
  1058. {
  1059. exponent = __exponentMax;
  1060. significandString = significandString + new string('0', numberOfTrailingZeroesToAdd);
  1061. }
  1062. }
  1063. }
  1064. else if (exponent < __exponentMin)
  1065. {
  1066. if (significandString == "0")
  1067. {
  1068. // since significand is zero simply use the smallest possible exponent
  1069. exponent = __exponentMin;
  1070. }
  1071. else
  1072. {
  1073. // use exact rounding to bring the exponent into range
  1074. var numberOfTrailingZeroesToRemove = __exponentMin - exponent;
  1075. if (numberOfTrailingZeroesToRemove < significandString.Length)
  1076. {
  1077. var trailingDigits = significandString.Substring(significandString.Length - numberOfTrailingZeroesToRemove);
  1078. if (Regex.IsMatch(trailingDigits, "^0+$"))
  1079. {
  1080. exponent = __exponentMin;
  1081. significandString = significandString.Substring(0, significandString.Length - numberOfTrailingZeroesToRemove);
  1082. }
  1083. }
  1084. }
  1085. }
  1086. else if (significandString.Length > 34)
  1087. {
  1088. // use exact rounding to reduce significand to 34 digits
  1089. var numberOfTrailingZeroesToRemove = significandString.Length - 34;
  1090. if (exponent + numberOfTrailingZeroesToRemove <= __exponentMax)
  1091. {
  1092. var trailingDigits = significandString.Substring(significandString.Length - numberOfTrailingZeroesToRemove);
  1093. if (Regex.IsMatch(trailingDigits, "^0+$"))
  1094. {
  1095. exponent += numberOfTrailingZeroesToRemove;
  1096. significandString = significandString.Substring(0, significandString.Length - numberOfTrailingZeroesToRemove);
  1097. }
  1098. }
  1099. }
  1100. return significandString;
  1101. }
  1102. private static Decimal128 DecreaseExponent(Decimal128 x, short goal)
  1103. {
  1104. if (Decimal128.IsZero(x))
  1105. {
  1106. // return a zero with the desired exponent
  1107. return Decimal128.FromComponents(Decimal128.IsNegative(x), goal, UInt128.Zero);
  1108. }
  1109. var exponent = GetExponent(x);
  1110. var significand = GetSignificand(x);
  1111. while (exponent > goal)
  1112. {
  1113. var significandTimes10 = UInt128.Multiply(significand, (uint)10);
  1114. if (significandTimes10.CompareTo(Decimal128.__maxSignificand) <= 0)
  1115. {
  1116. break;
  1117. }
  1118. exponent -= 1;
  1119. significand = significandTimes10;
  1120. }
  1121. return Decimal128.FromComponents(Decimal128.IsNegative(x), exponent, significand);
  1122. }
  1123. private static Decimal128 FromComponents(bool isNegative, short exponent, UInt128 significand)
  1124. {
  1125. if (exponent < __exponentMin || exponent > __exponentMax)
  1126. {
  1127. throw new ArgumentOutOfRangeException(nameof(exponent));
  1128. }
  1129. if (significand.CompareTo(__maxSignificand) > 0)
  1130. {
  1131. throw new ArgumentOutOfRangeException(nameof(significand));
  1132. }
  1133. var biasedExponent = MapExponentToDecimal128BiasedExponent(exponent);
  1134. var highBits = ((ulong)biasedExponent << 49) | significand.High;
  1135. if (isNegative)
  1136. {
  1137. highBits = Flags.SignBit | highBits;
  1138. }
  1139. return new Decimal128(highBits, significand.Low);
  1140. }
  1141. private static UInt128 GetSignificand(Decimal128 d)
  1142. {
  1143. return new UInt128(GetSignificandHighBits(d), GetSignificandLowBits(d));
  1144. }
  1145. private static Decimal128 IncreaseExponent(Decimal128 x, short goal)
  1146. {
  1147. if (Decimal128.IsZero(x))
  1148. {
  1149. // return a zero with the desired exponent
  1150. return Decimal128.FromComponents(Decimal128.IsNegative(x), goal, UInt128.Zero);
  1151. }
  1152. var exponent = GetExponent(x);
  1153. var significand = GetSignificand(x);
  1154. while (exponent < goal)
  1155. {
  1156. uint remainder;
  1157. var significandDividedBy10 = UInt128.Divide(significand, (uint)10, out remainder);
  1158. if (remainder != 0)
  1159. {
  1160. break;
  1161. }
  1162. exponent += 1;
  1163. significand = significandDividedBy10;
  1164. }
  1165. return Decimal128.FromComponents(Decimal128.IsNegative(x), exponent, significand);
  1166. }
  1167. private static short MapDecimal128BiasedExponentToExponent(short biasedExponent)
  1168. {
  1169. if (biasedExponent <= 6111)
  1170. {
  1171. return biasedExponent;
  1172. }
  1173. else
  1174. {
  1175. return (short)(biasedExponent - 12288);
  1176. }
  1177. }
  1178. private static ulong MapDecimal128HighBitsToIEEEHighBits(ulong highBits)
  1179. {
  1180. // for Decimal128Bias from 0 to 6111: IEEEBias = Decimal128Bias + 6176
  1181. // for Decimal128Bias from 6112 to 12287: IEEEBias = Decimal128Bias - 6112
  1182. if (Flags.IsFirstForm(highBits))
  1183. {
  1184. var exponentBits = highBits & Flags.FirstFormExponentBits;
  1185. if (exponentBits <= (6111L << 49))
  1186. {
  1187. return highBits + (6176L << 49);
  1188. }
  1189. else
  1190. {
  1191. return highBits - (6112L << 49);
  1192. }
  1193. }
  1194. else if (Flags.IsSecondForm(highBits))
  1195. {
  1196. var exponentBits = highBits & Flags.SecondFormExponentBits;
  1197. if (exponentBits <= (6111L << 47))
  1198. {
  1199. return highBits + (6176L << 47);
  1200. }
  1201. else
  1202. {
  1203. return highBits - (6112L << 47);
  1204. }
  1205. }
  1206. else
  1207. {
  1208. return highBits;
  1209. }
  1210. }
  1211. private static short MapExponentToDecimal128BiasedExponent(short exponent)
  1212. {
  1213. // internally we use a different bias than IEEE so that a Decimal128 struct filled with zero bytes is a true Decimal128 zero
  1214. // Decimal128Bias is defined as:
  1215. // exponents from 0 to 6111: biasedExponent = exponent
  1216. // exponents from -6176 to -1: biasedExponent = exponent + 12288
  1217. if (exponent >= 0)
  1218. {
  1219. return exponent;
  1220. }
  1221. else
  1222. {
  1223. return (short)(exponent + 12288);
  1224. }
  1225. }
  1226. private static ulong MapIEEEHighBitsToDecimal128HighBits(ulong highBits)
  1227. {
  1228. // for IEEEBias from 0 to 6175: Decimal128Bias = IEEEBias + 6112
  1229. // for IEEEBias from 6176 to 12287: Decimal128Bias = IEEEBias - 6176
  1230. if (Flags.IsFirstForm(highBits))
  1231. {
  1232. var exponentBits = highBits & Flags.FirstFormExponentBits;
  1233. if (exponentBits <= (6175L << 49))
  1234. {
  1235. return highBits + (6112L << 49);
  1236. }
  1237. else
  1238. {
  1239. return highBits - (6176L << 49);
  1240. }
  1241. }
  1242. else if (Flags.IsSecondForm(highBits))
  1243. {
  1244. var exponentBits = highBits & Flags.SecondFormExponentBits;
  1245. if (exponentBits <= (6175L << 47))
  1246. {
  1247. return highBits + (6112L << 47);
  1248. }
  1249. else
  1250. {
  1251. return highBits - (6176L << 47);
  1252. }
  1253. }
  1254. else
  1255. {
  1256. return highBits;
  1257. }
  1258. }
  1259. private static string RemoveLeadingZeroes(string significandString)
  1260. {
  1261. if (significandString[0] == '0' && significandString.Length > 1)
  1262. {
  1263. significandString = Regex.Replace(significandString, "^0+", "");
  1264. return significandString.Length == 0 ? "0" : significandString;
  1265. }
  1266. else
  1267. {
  1268. return significandString;
  1269. }
  1270. }
  1271. #endregion
  1272. // private fields
  1273. private readonly ulong _highBits;
  1274. private readonly ulong _lowBits;
  1275. // constructors
  1276. private Decimal128(ulong highBits, ulong lowBits)
  1277. {
  1278. _highBits = highBits;
  1279. _lowBits = lowBits;
  1280. }
  1281. /// <summary>
  1282. /// Initializes a new instance of the <see cref="Decimal128"/> struct.
  1283. /// </summary>
  1284. /// <param name="value">The value.</param>
  1285. public Decimal128(decimal value)
  1286. {
  1287. var bits = decimal.GetBits(value);
  1288. var isNegative = (bits[3] & 0x80000000) != 0;
  1289. var scale = (short)((bits[3] & 0x00FF0000) >> 16);
  1290. var exponent = (short)-scale;
  1291. var significandHigh = (ulong)(uint)bits[2];
  1292. var significandLow = ((ulong)(uint)bits[1] << 32) | (ulong)(uint)bits[0];
  1293. _highBits = (isNegative ? Flags.SignBit : 0) | ((ulong)MapExponentToDecimal128BiasedExponent(exponent) << 49) | significandHigh;
  1294. _lowBits = significandLow;
  1295. }
  1296. /// <summary>
  1297. /// Initializes a new instance of the <see cref="Decimal128"/> struct.
  1298. /// </summary>
  1299. /// <param name="value">The value.</param>
  1300. public Decimal128(double value)
  1301. {
  1302. // TODO: implement this more efficiently
  1303. var stringValue = value.ToString("G17");
  1304. var decimal128Value = Decimal128.Parse(stringValue);
  1305. _highBits = MapIEEEHighBitsToDecimal128HighBits(decimal128Value.GetIEEEHighBits());
  1306. _lowBits = decimal128Value.GetIEEELowBits();
  1307. }
  1308. /// <summary>
  1309. /// Initializes a new instance of the <see cref="Decimal128"/> struct.
  1310. /// </summary>
  1311. /// <param name="value">The value.</param>
  1312. public Decimal128(float value)
  1313. {
  1314. // TODO: implement this more efficiently
  1315. var stringValue = value.ToString("G17");
  1316. var decimal128Value = Decimal128.Parse(stringValue);
  1317. _highBits = MapIEEEHighBitsToDecimal128HighBits(decimal128Value.GetIEEEHighBits());
  1318. _lowBits = decimal128Value.GetIEEELowBits();
  1319. }
  1320. /// <summary>
  1321. /// Initializes a new instance of the <see cref="Decimal128"/> struct.
  1322. /// </summary>
  1323. /// <param name="value">The value.</param>
  1324. public Decimal128(int value)
  1325. {
  1326. if (value >= 0)
  1327. {
  1328. _highBits = 0;
  1329. _lowBits = (ulong)value;
  1330. }
  1331. else
  1332. {
  1333. _highBits = Flags.SignBit;
  1334. _lowBits = value == int.MinValue ? (ulong)int.MaxValue + 1 : (ulong)-value;
  1335. }
  1336. }
  1337. /// <summary>
  1338. /// Initializes a new instance of the <see cref="Decimal128"/> struct.
  1339. /// </summary>
  1340. /// <param name="value">The value.</param>
  1341. public Decimal128(long value)
  1342. {
  1343. if (value >= 0)
  1344. {
  1345. _highBits = 0;
  1346. _lowBits = (ulong)value;
  1347. }
  1348. else
  1349. {
  1350. _highBits = Flags.SignBit;
  1351. _lowBits = value == long.MinValue ? (ulong)long.MaxValue + 1 : (ulong)-value;
  1352. }
  1353. }
  1354. /// <summary>
  1355. /// Initializes a new instance of the <see cref="Decimal128"/> struct.
  1356. /// </summary>
  1357. /// <param name="value">The value.</param>
  1358. [CLSCompliant(false)]
  1359. public Decimal128(uint value)
  1360. {
  1361. _highBits = 0;
  1362. _lowBits = value;
  1363. }
  1364. /// <summary>
  1365. /// Initializes a new instance of the <see cref="Decimal128"/> struct.
  1366. /// </summary>
  1367. /// <param name="value">The value.</param>
  1368. [CLSCompliant(false)]
  1369. public Decimal128(ulong value)
  1370. {
  1371. _highBits = 0;
  1372. _lowBits = value;
  1373. }
  1374. // public methods
  1375. /// <inheritdoc />
  1376. public int CompareTo(Decimal128 other)
  1377. {
  1378. return Decimal128.Compare(this, other);
  1379. }
  1380. /// <inheritdoc />
  1381. public bool Equals(Decimal128 other)
  1382. {
  1383. return Decimal128.Equals(this, other);
  1384. }
  1385. /// <inheritdoc />
  1386. public override bool Equals(object obj)
  1387. {
  1388. if (obj == null || obj.GetType() != typeof(Decimal128))
  1389. {
  1390. return false;
  1391. }
  1392. else
  1393. {
  1394. return Equals((Decimal128)obj);
  1395. }
  1396. }
  1397. /// <inheritdoc />
  1398. public override int GetHashCode()
  1399. {
  1400. int hash = 17;
  1401. hash = 37 * hash + _highBits.GetHashCode();
  1402. hash = 37 * hash + _lowBits.GetHashCode();
  1403. return hash;
  1404. }
  1405. /// <summary>
  1406. /// Gets the high order 64 bits of the binary representation of this instance.
  1407. /// </summary>
  1408. /// <returns>The high order 64 bits of the binary representation of this instance.</returns>
  1409. [CLSCompliant(false)]
  1410. public ulong GetIEEEHighBits()
  1411. {
  1412. return MapDecimal128HighBitsToIEEEHighBits(_highBits);
  1413. }
  1414. /// <summary>
  1415. /// Gets the low order 64 bits of the binary representation of this instance.
  1416. /// </summary>
  1417. /// <returns>The low order 64 bits of the binary representation of this instance.</returns>
  1418. [CLSCompliant(false)]
  1419. public ulong GetIEEELowBits()
  1420. {
  1421. return _lowBits;
  1422. }
  1423. /// <inheritdoc />
  1424. public override string ToString()
  1425. {
  1426. if (Flags.IsFirstForm(_highBits))
  1427. {
  1428. var exponent = GetExponent(this);
  1429. var significand = GetSignificand(this);
  1430. var coefficientString = significand.ToString();
  1431. var adjustedExponent = exponent + coefficientString.Length - 1;
  1432. string result;
  1433. if (exponent > 0 || adjustedExponent < -6)
  1434. {
  1435. result = ToStringWithExponentialNotation(coefficientString, adjustedExponent);
  1436. }
  1437. else
  1438. {
  1439. result = ToStringWithoutExponentialNotation(coefficientString, exponent);
  1440. }
  1441. if (Flags.IsNegative(_highBits))
  1442. {
  1443. result = "-" + result;
  1444. }
  1445. return result;
  1446. }
  1447. else if (Flags.IsSecondForm(_highBits))
  1448. {
  1449. // invalid representation treated as zero
  1450. var exponent = GetExponent(this);
  1451. if (exponent == 0)
  1452. {
  1453. return Flags.IsNegative(_highBits) ? "-0" : "0";
  1454. }
  1455. else
  1456. {
  1457. var exponentString = exponent.ToString(NumberFormatInfo.InvariantInfo);
  1458. if (exponent > 0)
  1459. {
  1460. exponentString = "+" + exponentString;
  1461. }
  1462. return (Flags.IsNegative(_highBits) ? "-0E" : "0E") + exponentString;
  1463. }
  1464. }
  1465. else if (Flags.IsNegativeInfinity(_highBits))
  1466. {
  1467. return "-Infinity";
  1468. }
  1469. else if (Flags.IsPositiveInfinity(_highBits))
  1470. {
  1471. return "Infinity";
  1472. }
  1473. else
  1474. {
  1475. return "NaN";
  1476. }
  1477. }
  1478. // explicit IConvertible implementation
  1479. TypeCode IConvertible.GetTypeCode()
  1480. {
  1481. return TypeCode.Object;
  1482. }
  1483. bool IConvertible.ToBoolean(IFormatProvider provider)
  1484. {
  1485. return !(Decimal128.Equals(this, Decimal128.Zero) || Decimal128.IsNaN(this));
  1486. }
  1487. byte IConvertible.ToByte(IFormatProvider provider)
  1488. {
  1489. return Decimal128.ToByte(this);
  1490. }
  1491. char IConvertible.ToChar(IFormatProvider provider)
  1492. {
  1493. throw new InvalidCastException("Invalid cast from Decima128 to Char.");
  1494. }
  1495. DateTime IConvertible.ToDateTime(IFormatProvider provider)
  1496. {
  1497. throw new InvalidCastException("Invalid cast from Decima128 to DateTime.");
  1498. }
  1499. decimal IConvertible.ToDecimal(IFormatProvider provider)
  1500. {
  1501. return Decimal128.ToDecimal(this);
  1502. }
  1503. double IConvertible.ToDouble(IFormatProvider provider)
  1504. {
  1505. return Decimal128.ToDouble(this);
  1506. }
  1507. short IConvertible.ToInt16(IFormatProvider provider)
  1508. {
  1509. return Decimal128.ToInt16(this);
  1510. }
  1511. int IConvertible.ToInt32(IFormatProvider provider)
  1512. {
  1513. return Decimal128.ToInt32(this);
  1514. }
  1515. long IConvertible.ToInt64(IFormatProvider provider)
  1516. {
  1517. return Decimal128.ToInt64(this);
  1518. }
  1519. sbyte IConvertible.ToSByte(IFormatProvider provider)
  1520. {
  1521. return Decimal128.ToSByte(this);
  1522. }
  1523. float IConvertible.ToSingle(IFormatProvider provider)
  1524. {
  1525. return Decimal128.ToSingle(this);
  1526. }
  1527. string IConvertible.ToString(IFormatProvider provider)
  1528. {
  1529. return ToString();
  1530. }
  1531. object IConvertible.ToType(Type conversionType, IFormatProvider provider)
  1532. {
  1533. var convertible = (IConvertible)this;
  1534. switch (Type.GetTypeCode(conversionType))
  1535. {
  1536. case TypeCode.Boolean: return convertible.ToBoolean(provider);
  1537. case TypeCode.Byte: return convertible.ToByte(provider);
  1538. case TypeCode.Char: return convertible.ToChar(provider);
  1539. case TypeCode.DateTime: return convertible.ToDateTime(provider);
  1540. case TypeCode.Decimal: return convertible.ToDecimal(provider);
  1541. case TypeCode.Double: return convertible.ToDouble(provider);
  1542. case TypeCode.Int16: return convertible.ToInt16(provider);
  1543. case TypeCode.Int32: return convertible.ToInt32(provider);
  1544. case TypeCode.Int64: return convertible.ToInt64(provider);
  1545. case TypeCode.SByte: return convertible.ToSByte(provider);
  1546. case TypeCode.Single: return convertible.ToSingle(provider);
  1547. case TypeCode.String: return convertible.ToString(provider);
  1548. case TypeCode.UInt16: return convertible.ToUInt16(provider);
  1549. case TypeCode.UInt32: return convertible.ToUInt32(provider);
  1550. case TypeCode.UInt64: return convertible.ToUInt64(provider);
  1551. default: throw new InvalidCastException();
  1552. }
  1553. }
  1554. ushort IConvertible.ToUInt16(IFormatProvider provider)
  1555. {
  1556. return Decimal128.ToUInt16(this);
  1557. }
  1558. uint IConvertible.ToUInt32(IFormatProvider provider)
  1559. {
  1560. return Decimal128.ToUInt32(this);
  1561. }
  1562. ulong IConvertible.ToUInt64(IFormatProvider provider)
  1563. {
  1564. return Decimal128.ToUInt64(this);
  1565. }
  1566. // private methods
  1567. private string ToStringWithExponentialNotation(string coefficientString, int adjustedExponent)
  1568. {
  1569. if (coefficientString.Length > 1)
  1570. {
  1571. coefficientString = coefficientString.Substring(0, 1) + "." + coefficientString.Substring(1);
  1572. }
  1573. var exponentString = adjustedExponent.ToString(NumberFormatInfo.InvariantInfo);
  1574. if (adjustedExponent >= 0)
  1575. {
  1576. exponentString = "+" + exponentString;
  1577. }
  1578. return coefficientString + "E" + exponentString;
  1579. }
  1580. private string ToStringWithoutExponentialNotation(string coefficientString, int exponent)
  1581. {
  1582. if (exponent == 0)
  1583. {
  1584. return coefficientString;
  1585. }
  1586. else
  1587. {
  1588. var exponentAbsoluteValue = Math.Abs(exponent);
  1589. var minimumCoefficientStringLength = exponentAbsoluteValue + 1;
  1590. if (coefficientString.Length < minimumCoefficientStringLength)
  1591. {
  1592. coefficientString = coefficientString.PadLeft(minimumCoefficientStringLength, '0');
  1593. }
  1594. var decimalPointIndex = coefficientString.Length - exponentAbsoluteValue;
  1595. return coefficientString.Substring(0, decimalPointIndex) + "." + coefficientString.Substring(decimalPointIndex);
  1596. }
  1597. }
  1598. private static bool TryTruncateToUInt64(Decimal128 d, ulong maxNegativeValue, ulong maxPositiveValue, out ulong value)
  1599. {
  1600. if (Decimal128.IsZero(d))
  1601. {
  1602. value = 0;
  1603. return true;
  1604. }
  1605. var exponent = Decimal128.GetExponent(d);
  1606. var significand = Decimal128.GetSignificand(d);
  1607. if (exponent < 0)
  1608. {
  1609. while (exponent < 0)
  1610. {
  1611. uint remainder; // ignored because we are truncating
  1612. significand = UInt128.Divide(significand, (uint)10, out remainder);
  1613. if (significand.Equals(UInt128.Zero))
  1614. {
  1615. value = 0;
  1616. return true;
  1617. }
  1618. exponent += 1;
  1619. }
  1620. }
  1621. else if (exponent > 0)
  1622. {
  1623. while (exponent > 0)
  1624. {
  1625. significand = UInt128.Multiply(significand, (uint)10);
  1626. if (significand.CompareTo(__maxSignificand) > 0)
  1627. {
  1628. value = 0;
  1629. return false;
  1630. }
  1631. exponent -= 1;
  1632. }
  1633. }
  1634. if (exponent != 0)
  1635. {
  1636. value = 0;
  1637. return false;
  1638. }
  1639. if (significand.High != 0 || significand.Low > (Decimal128.IsNegative(d) ? maxNegativeValue : maxPositiveValue))
  1640. {
  1641. value = 0;
  1642. return false;
  1643. }
  1644. value = significand.Low;
  1645. return true;
  1646. }
  1647. // nested types
  1648. private class Decimal128Comparer : IComparer<Decimal128>
  1649. {
  1650. #region static
  1651. // private static fields
  1652. private static readonly Decimal128Comparer __instance = new Decimal128Comparer();
  1653. // public static properties
  1654. public static Decimal128Comparer Instance
  1655. {
  1656. get { return __instance; }
  1657. }
  1658. #endregion
  1659. // public methods
  1660. public int Compare(Decimal128 x, Decimal128 y)
  1661. {
  1662. var xType = GetDecimal128Type(x);
  1663. var yType = GetDecimal128Type(y);
  1664. var result = xType.CompareTo(yType);
  1665. if (result == 0 && xType == Decimal128Type.Number)
  1666. {
  1667. return CompareNumbers(x, y);
  1668. }
  1669. else
  1670. {
  1671. return result;
  1672. }
  1673. }
  1674. // private methods
  1675. private Decimal128Type GetDecimal128Type(Decimal128 x)
  1676. {
  1677. if (Decimal128.IsNaN(x)) { return Decimal128Type.NaN; }
  1678. else if (Decimal128.IsNegativeInfinity(x)) { return Decimal128Type.NegativeInfinity; }
  1679. else if (Decimal128.IsPositiveInfinity(x)) { return Decimal128Type.PositiveInfity; }
  1680. else { return Decimal128Type.Number; }
  1681. }
  1682. private int CompareNumbers(Decimal128 x, Decimal128 y)
  1683. {
  1684. var xClass = GetNumberClass(x);
  1685. var yClass = GetNumberClass(y);
  1686. var result = xClass.CompareTo(yClass);
  1687. if (result == 0)
  1688. {
  1689. if (xClass == NumberClass.Negative)
  1690. {
  1691. return CompareNegativeNumbers(x, y);
  1692. }
  1693. else if (xClass == NumberClass.Positive)
  1694. {
  1695. return ComparePositiveNumbers(x, y);
  1696. }
  1697. else
  1698. {
  1699. return 0; // else all Zeroes compare equal
  1700. }
  1701. }
  1702. else
  1703. {
  1704. return result;
  1705. }
  1706. }
  1707. private NumberClass GetNumberClass(Decimal128 x)
  1708. {
  1709. if (Decimal128.IsZero(x)) { return NumberClass.Zero; } // must test for Zero first
  1710. else if (Decimal128.IsNegative(x)) { return NumberClass.Negative; }
  1711. else { return NumberClass.Positive; }
  1712. }
  1713. private int CompareNegativeNumbers(Decimal128 x, Decimal128 y)
  1714. {
  1715. return -ComparePositiveNumbers(Decimal128.Negate(x), Decimal128.Negate(y));
  1716. }
  1717. private int ComparePositiveNumbers(Decimal128 x, Decimal128 y)
  1718. {
  1719. var xExponent = GetExponent(x);
  1720. var yExponent = GetExponent(y);
  1721. var exponentDifference = Math.Abs(xExponent - yExponent);
  1722. if (exponentDifference <= 66)
  1723. {
  1724. // we may or may not be able to make the exponents equal but we won't know until we try
  1725. // but we do know we can't eliminate an exponent difference larger than 66
  1726. if (xExponent < yExponent)
  1727. {
  1728. x = IncreaseExponent(x, yExponent);
  1729. y = DecreaseExponent(y, xExponent);
  1730. }
  1731. else if (xExponent > yExponent)
  1732. {
  1733. x = DecreaseExponent(x, yExponent);
  1734. y = IncreaseExponent(y, xExponent);
  1735. }
  1736. }
  1737. if (xExponent == yExponent)
  1738. {
  1739. return GetSignificand(x).CompareTo(GetSignificand(y));
  1740. }
  1741. else
  1742. {
  1743. return xExponent.CompareTo(yExponent);
  1744. }
  1745. }
  1746. private enum Decimal128Type { NaN, NegativeInfinity, Number, PositiveInfity }; // the order matters
  1747. private enum NumberClass { Negative, Zero, Positive }; // the order matters
  1748. }
  1749. private static class Flags
  1750. {
  1751. public const ulong SignBit = 0x8000000000000000;
  1752. public const ulong FirstFormLeadingBits = 0x6000000000000000;
  1753. public const ulong FirstFormLeadingBitsMax = 0x4000000000000000;
  1754. public const ulong FirstFormExponentBits = 0x7FFE000000000000;
  1755. public const ulong FirstFormSignificandBits = 0x0001FFFFFFFFFFFF;
  1756. public const ulong SecondFormLeadingBits = 0x7800000000000000;
  1757. public const ulong SecondFormLeadingBitsMin = 0x6000000000000000;
  1758. public const ulong SecondFormLeadingBitsMax = 0x7000000000000000;
  1759. public const ulong SecondFormExponentBits = 0x1FFF800000000000;
  1760. public const ulong InfinityBits = 0x7C00000000000000;
  1761. public const ulong Infinity = 0x7800000000000000;
  1762. public const ulong SignedInfinityBits = 0xFC00000000000000;
  1763. public const ulong PositiveInfinity = 0x7800000000000000;
  1764. public const ulong NegativeInfinity = 0xF800000000000000;
  1765. public const ulong PartialNaNBits = 0x7C00000000000000;
  1766. public const ulong PartialNaN = 0x7C00000000000000;
  1767. public const ulong NaNBits = 0x7E00000000000000;
  1768. public const ulong QNaN = 0x7C00000000000000;
  1769. public const ulong SNaN = 0x7E00000000000000;
  1770. public static bool IsFirstForm(ulong highBits)
  1771. {
  1772. return (highBits & Flags.FirstFormLeadingBits) <= Flags.FirstFormLeadingBitsMax;
  1773. }
  1774. public static bool IsInfinity(ulong highBits)
  1775. {
  1776. return (highBits & Flags.InfinityBits) == Flags.Infinity;
  1777. }
  1778. public static bool IsNaN(ulong highBits)
  1779. {
  1780. return (highBits & Flags.PartialNaNBits) == Flags.PartialNaN;
  1781. }
  1782. public static bool IsNegative(ulong highBits)
  1783. {
  1784. return (highBits & Flags.SignBit) != 0;
  1785. }
  1786. public static bool IsNegativeInfinity(ulong highBits)
  1787. {
  1788. return (highBits & Flags.SignedInfinityBits) == Flags.NegativeInfinity;
  1789. }
  1790. public static bool IsPositiveInfinity(ulong highBits)
  1791. {
  1792. return (highBits & Flags.SignedInfinityBits) == Flags.PositiveInfinity;
  1793. }
  1794. public static bool IsQNaN(ulong highBits)
  1795. {
  1796. return (highBits & Flags.NaNBits) == Flags.QNaN;
  1797. }
  1798. public static bool IsSecondForm(ulong highBits)
  1799. {
  1800. var secondFormLeadingBits = highBits & Flags.SecondFormLeadingBits;
  1801. return secondFormLeadingBits >= Flags.SecondFormLeadingBitsMin & secondFormLeadingBits <= Flags.SecondFormLeadingBitsMax;
  1802. }
  1803. public static bool IsSNaN(ulong highBits)
  1804. {
  1805. return (highBits & Flags.NaNBits) == Flags.SNaN;
  1806. }
  1807. }
  1808. }
  1809. }