Decimal128.cs 73 KB

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