Decimal128.cs 73 KB

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