No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

BurstString.Float.cs 82KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924
  1. using System;
  2. using System.Runtime.CompilerServices;
  3. using System.Runtime.InteropServices;
  4. namespace Unity.Burst
  5. {
  6. #if BURST_COMPILER_SHARED
  7. internal static partial class BurstStringInternal
  8. #else
  9. internal static partial class BurstString
  10. #endif
  11. {
  12. // This file provides an implementation for formatting floating point numbers that is compatible
  13. // with Burst
  14. // ------------------------------------------------------------------------------
  15. // Part of code translated to C# from http://www.ryanjuckett.com/programming/printing-floating-point-numbers
  16. // with the following license:
  17. /******************************************************************************
  18. Copyright (c) 2014 Ryan Juckett
  19. http://www.ryanjuckett.com/
  20. This software is provided 'as-is', without any express or implied
  21. warranty. In no event will the authors be held liable for any damages
  22. arising from the use of this software.
  23. Permission is granted to anyone to use this software for any purpose,
  24. including commercial applications, and to alter it and redistribute it
  25. freely, subject to the following restrictions:
  26. 1. The origin of this software must not be misrepresented; you must not
  27. claim that you wrote the original software. If you use this software
  28. in a product, an acknowledgment in the product documentation would be
  29. appreciated but is not required.
  30. 2. Altered source versions must be plainly marked as such, and must not be
  31. misrepresented as being the original software.
  32. 3. This notice may not be removed or altered from any source
  33. distribution.
  34. ******************************************************************************/
  35. //******************************************************************************
  36. // Get the log base 2 of a 32-bit unsigned integer.
  37. // http://graphics.stanford.edu/~seander/bithacks.html#IntegerLogLookup
  38. //******************************************************************************
  39. private static readonly byte[] logTable = new byte[256]
  40. {
  41. 0, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3,
  42. 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  43. 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  44. 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  45. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  46. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  47. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  48. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  49. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  50. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  51. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  52. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  53. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  54. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  55. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  56. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7
  57. };
  58. private static uint LogBase2(uint val)
  59. {
  60. uint temp;
  61. temp = val >> 24;
  62. if (temp != 0)
  63. return (uint)(24 + logTable[(int)temp]);
  64. temp = val >> 16;
  65. if (temp != 0)
  66. return (uint)(16 + logTable[temp]);
  67. temp = val >> 8;
  68. if (temp != 0)
  69. return (uint)(8 + logTable[temp]);
  70. return logTable[val];
  71. }
  72. //******************************************************************************
  73. // This structure stores a high precision unsigned integer. It uses a buffer
  74. // of 32 bit integer blocks along with a length. The lowest bits of the integer
  75. // are stored at the start of the buffer and the length is set to the minimum
  76. // value that contains the integer. Thus, there are never any zero blocks at the
  77. // end of the buffer.
  78. //******************************************************************************
  79. public unsafe struct tBigInt
  80. {
  81. //******************************************************************************
  82. // Maximum number of 32 bit blocks needed in high precision arithmetic
  83. // to print out 64 bit IEEE floating point values.
  84. //******************************************************************************
  85. const int c_BigInt_MaxBlocks = 35;
  86. //// Copy integer
  87. //tBigInt & operator=(tBigInt &rhs)
  88. //{
  89. // uint length = rhs.m_length;
  90. // uint* pLhsCur = m_blocks;
  91. // for (uint* pRhsCur = rhs.m_blocks, *pRhsEnd = pRhsCur + length;
  92. // pRhsCur != pRhsEnd;
  93. // ++pLhsCur, ++pRhsCur)
  94. // {
  95. // *pLhsCur = *pRhsCur;
  96. // }
  97. // m_length = length;
  98. // return *this;
  99. //}
  100. // Data accessors
  101. public int GetLength() { return m_length; }
  102. public uint GetBlock(int idx) { return m_blocks[idx]; }
  103. // Zero helper functions
  104. public void SetZero() { m_length = 0; }
  105. public bool IsZero() { return m_length == 0; }
  106. // Basic type accessors
  107. public void SetU64(ulong val)
  108. {
  109. if (val > 0xFFFFFFFF)
  110. {
  111. m_blocks[0] = (uint)(val & 0xFFFFFFFF);
  112. m_blocks[1] = (uint)(val >> 32 & 0xFFFFFFFF);
  113. m_length = 2;
  114. }
  115. else if (val != 0)
  116. {
  117. m_blocks[0] = (uint)(val & 0xFFFFFFFF);
  118. m_length = 1;
  119. }
  120. else
  121. {
  122. m_length = 0;
  123. }
  124. }
  125. public void SetU32(uint val)
  126. {
  127. if (val != 0)
  128. {
  129. m_blocks[0] = val;
  130. m_length = (val != 0) ? 1 : 0;
  131. }
  132. else
  133. {
  134. m_length = 0;
  135. }
  136. }
  137. public uint GetU32() { return (m_length == 0) ? 0 : m_blocks[0]; }
  138. // Member data
  139. public int m_length;
  140. public fixed uint m_blocks[c_BigInt_MaxBlocks];
  141. }
  142. //******************************************************************************
  143. // Returns 0 if (lhs = rhs), negative if (lhs < rhs), positive if (lhs > rhs)
  144. //******************************************************************************
  145. private static unsafe int BigInt_Compare(in tBigInt lhs, in tBigInt rhs)
  146. {
  147. // A bigger length implies a bigger number.
  148. int lengthDiff = lhs.m_length - rhs.m_length;
  149. if (lengthDiff != 0)
  150. return lengthDiff;
  151. // Compare blocks one by one from high to low.
  152. for (int i = (int)lhs.m_length - 1; i >= 0; --i)
  153. {
  154. if (lhs.m_blocks[i] == rhs.m_blocks[i])
  155. continue;
  156. else if (lhs.m_blocks[i] > rhs.m_blocks[i])
  157. return 1;
  158. else
  159. return -1;
  160. }
  161. // no blocks differed
  162. return 0;
  163. }
  164. //******************************************************************************
  165. // result = lhs + rhs
  166. //******************************************************************************
  167. private static unsafe void BigInt_Add(out tBigInt pResult, in tBigInt lhs, in tBigInt rhs)
  168. {
  169. if (lhs.m_length < rhs.m_length)
  170. {
  171. BigInt_Add_internal(out pResult, rhs, lhs);
  172. }
  173. else
  174. {
  175. BigInt_Add_internal(out pResult, lhs, rhs);
  176. }
  177. }
  178. private static unsafe void BigInt_Add_internal(out tBigInt pResult, in tBigInt pLarge, in tBigInt pSmall)
  179. {
  180. int largeLen = pLarge.m_length;
  181. int smallLen = pSmall.m_length;
  182. // The output will be at least as long as the largest input
  183. pResult.m_length = largeLen;
  184. // Add each block and add carry the overflow to the next block
  185. ulong carry = 0;
  186. fixed (uint * pLargeCur1 = pLarge.m_blocks)
  187. fixed (uint * pSmallCur1 = pSmall.m_blocks)
  188. fixed (uint * pResultCur1 = pResult.m_blocks)
  189. {
  190. uint* pLargeCur = pLargeCur1;
  191. uint* pSmallCur = pSmallCur1;
  192. uint* pResultCur = pResultCur1;
  193. uint* pLargeEnd = pLargeCur + largeLen;
  194. uint* pSmallEnd = pSmallCur + smallLen;
  195. while (pSmallCur != pSmallEnd)
  196. {
  197. ulong sum = carry + (ulong) (*pLargeCur) + (ulong) (*pSmallCur);
  198. carry = sum >> 32;
  199. (*pResultCur) = (uint)(sum & 0xFFFFFFFF);
  200. ++pLargeCur;
  201. ++pSmallCur;
  202. ++pResultCur;
  203. }
  204. // Add the carry to any blocks that only exist in the large operand
  205. while (pLargeCur != pLargeEnd)
  206. {
  207. ulong sum = carry + (ulong) (*pLargeCur);
  208. carry = sum >> 32;
  209. (*pResultCur) = (uint)(sum & 0xFFFFFFFF);
  210. ++pLargeCur;
  211. ++pResultCur;
  212. }
  213. // If there's still a carry, append a new block
  214. if (carry != 0)
  215. {
  216. //RJ_ASSERT(carry == 1);
  217. //RJ_ASSERT((uint)(pResultCur - pResult.m_blocks) == largeLen && (largeLen < c_BigInt_MaxBlocks));
  218. *pResultCur = 1;
  219. pResult.m_length = largeLen + 1;
  220. }
  221. else
  222. {
  223. pResult.m_length = largeLen;
  224. }
  225. }
  226. }
  227. //******************************************************************************
  228. // result = lhs * rhs
  229. //******************************************************************************
  230. private static unsafe void BigInt_Multiply(out tBigInt pResult, in tBigInt lhs, in tBigInt rhs)
  231. {
  232. if (lhs.m_length < rhs.m_length)
  233. {
  234. BigInt_Multiply_internal(out pResult, rhs, lhs);
  235. }
  236. else
  237. {
  238. BigInt_Multiply_internal(out pResult, lhs, rhs);
  239. }
  240. }
  241. private static unsafe void BigInt_Multiply_internal(out tBigInt pResult, in tBigInt pLarge, in tBigInt pSmall)
  242. {
  243. // set the maximum possible result length
  244. int maxResultLen = pLarge.m_length + pSmall.m_length;
  245. // RJ_ASSERT( maxResultLen <= c_BigInt_MaxBlocks );
  246. // clear the result data
  247. // uint * pCur = pResult.m_blocks, *pEnd = pCur + maxResultLen; pCur != pEnd; ++pCur
  248. for (int i = 0; i < maxResultLen; i++)
  249. pResult.m_blocks[i] = 0;
  250. // perform standard long multiplication
  251. fixed (uint *pLargeBeg1 = pLarge.m_blocks)
  252. {
  253. uint* pLargeBeg = pLargeBeg1;
  254. uint* pLargeEnd = pLargeBeg + pLarge.m_length;
  255. // for each small block
  256. fixed (uint* pResultStart1 = pResult.m_blocks)
  257. fixed (uint* pSmallCur1 = pSmall.m_blocks)
  258. {
  259. uint* pSmallCur = pSmallCur1;
  260. uint* pSmallEnd = pSmallCur + pSmall.m_length;
  261. uint* pResultStart = pResultStart1;
  262. for (; pSmallCur != pSmallEnd; ++pSmallCur, ++pResultStart)
  263. {
  264. // if non-zero, multiply against all the large blocks and add into the result
  265. uint multiplier = *pSmallCur;
  266. if (multiplier != 0)
  267. {
  268. uint* pLargeCur = pLargeBeg;
  269. uint* pResultCur = pResultStart;
  270. ulong carry = 0;
  271. do
  272. {
  273. ulong product = (*pResultCur) + (*pLargeCur) * (ulong) multiplier + carry;
  274. carry = product >> 32;
  275. *pResultCur = (uint)(product & 0xFFFFFFFF);
  276. ++pLargeCur;
  277. ++pResultCur;
  278. } while (pLargeCur != pLargeEnd);
  279. //RJ_ASSERT(pResultCur < pResult.m_blocks + maxResultLen);
  280. *pResultCur = (uint) (carry & 0xFFFFFFFF);
  281. }
  282. }
  283. // check if the terminating block has no set bits
  284. if (maxResultLen > 0 && pResult.m_blocks[maxResultLen - 1] == 0)
  285. pResult.m_length = maxResultLen - 1;
  286. else
  287. pResult.m_length = maxResultLen;
  288. }
  289. }
  290. }
  291. //******************************************************************************
  292. // result = lhs * rhs
  293. //******************************************************************************
  294. private static unsafe void BigInt_Multiply(out tBigInt pResult, in tBigInt lhs, uint rhs)
  295. {
  296. // perform long multiplication
  297. uint carry = 0;
  298. fixed (uint* pResultCur1 = pResult.m_blocks)
  299. fixed (uint* pLhsCur1 = lhs.m_blocks)
  300. {
  301. uint* pResultCur = pResultCur1;
  302. uint* pLhsCur = pLhsCur1;
  303. uint* pLhsEnd = pLhsCur + lhs.m_length;
  304. for (; pLhsCur != pLhsEnd; ++pLhsCur, ++pResultCur)
  305. {
  306. ulong product = (ulong) (*pLhsCur) * rhs + carry;
  307. *pResultCur = (uint) (product & 0xFFFFFFFF);
  308. carry = (uint)(product >> 32);
  309. }
  310. // if there is a remaining carry, grow the array
  311. if (carry != 0)
  312. {
  313. // grow the array
  314. //RJ_ASSERT(lhs.m_length + 1 <= c_BigInt_MaxBlocks);
  315. *pResultCur = (uint) carry;
  316. pResult.m_length = lhs.m_length + 1;
  317. }
  318. else
  319. {
  320. pResult.m_length = lhs.m_length;
  321. }
  322. }
  323. }
  324. //******************************************************************************
  325. // result = in * 2
  326. //******************************************************************************
  327. private static unsafe void BigInt_Multiply2(out tBigInt pResult, in tBigInt input)
  328. {
  329. // shift all the blocks by one
  330. uint carry = 0;
  331. fixed (uint* pResultCur1 = pResult.m_blocks)
  332. fixed (uint* pLhsCur1 = input.m_blocks)
  333. {
  334. uint* pResultCur = pResultCur1;
  335. uint* pLhsCur = pLhsCur1;
  336. uint* pLhsEnd = pLhsCur + input.m_length;
  337. for (; pLhsCur != pLhsEnd; ++pLhsCur, ++pResultCur)
  338. {
  339. uint cur = *pLhsCur;
  340. *pResultCur = (cur << 1) | carry;
  341. carry = cur >> 31;
  342. }
  343. if (carry != 0)
  344. {
  345. // grow the array
  346. // RJ_ASSERT(input.m_length + 1 <= c_BigInt_MaxBlocks);
  347. *pResultCur = carry;
  348. pResult.m_length = input.m_length + 1;
  349. }
  350. else
  351. {
  352. pResult.m_length = input.m_length;
  353. }
  354. }
  355. }
  356. //******************************************************************************
  357. // result = result * 2
  358. //******************************************************************************
  359. private static unsafe void BigInt_Multiply2(ref tBigInt pResult)
  360. {
  361. // shift all the blocks by one
  362. uint carry = 0;
  363. fixed (uint* pCur1 = pResult.m_blocks)
  364. {
  365. uint* pCur = pCur1;
  366. uint* pEnd = pCur + pResult.m_length;
  367. for (; pCur != pEnd; ++pCur)
  368. {
  369. uint cur = *pCur;
  370. *pCur = (cur << 1) | carry;
  371. carry = cur >> 31;
  372. }
  373. if (carry != 0)
  374. {
  375. // grow the array
  376. // RJ_ASSERT(pResult.m_length + 1 <= c_BigInt_MaxBlocks);
  377. *pCur = carry;
  378. ++pResult.m_length;
  379. }
  380. }
  381. }
  382. //******************************************************************************
  383. // result = result * 10
  384. //******************************************************************************
  385. private static unsafe void BigInt_Multiply10(ref tBigInt pResult)
  386. {
  387. // multiply all the blocks
  388. ulong carry = 0;
  389. fixed (uint* pCur1 = pResult.m_blocks)
  390. {
  391. uint* pCur = pCur1;
  392. uint* pEnd = pCur + pResult.m_length;
  393. for (; pCur != pEnd; ++pCur)
  394. {
  395. ulong product = (ulong) (*pCur) * 10 + carry;
  396. (*pCur) = (uint) (product & 0xFFFFFFFF);
  397. carry = product >> 32;
  398. }
  399. if (carry != 0)
  400. {
  401. // grow the array
  402. //RJ_ASSERT(pResult.m_length + 1 <= c_BigInt_MaxBlocks);
  403. *pCur = (uint) carry;
  404. ++pResult.m_length;
  405. }
  406. }
  407. }
  408. //******************************************************************************
  409. //******************************************************************************
  410. private static readonly uint[] g_PowerOf10_U32 = new uint[]
  411. {
  412. 1, // 10 ^ 0
  413. 10, // 10 ^ 1
  414. 100, // 10 ^ 2
  415. 1000, // 10 ^ 3
  416. 10000, // 10 ^ 4
  417. 100000, // 10 ^ 5
  418. 1000000, // 10 ^ 6
  419. 10000000, // 10 ^ 7
  420. };
  421. //******************************************************************************
  422. // Note: This has a lot of wasted space in the big integer structures of the
  423. // early table entries. It wouldn't be terribly hard to make the multiply
  424. // function work on integer pointers with an array length instead of
  425. // the tBigInt struct which would allow us to store a minimal amount of
  426. // data here.
  427. //******************************************************************************
  428. private static unsafe tBigInt g_PowerOf10_Big(int i)
  429. {
  430. tBigInt result;
  431. // 10 ^ 8
  432. if (i == 0)
  433. {
  434. // { 1, { 100000000 } },
  435. result.m_length = 1;
  436. result.m_blocks[0] = 100000000;
  437. }
  438. else if (i == 1)
  439. {
  440. // 10 ^ 16
  441. // { 2, { 0x6fc10000, 0x002386f2 } },
  442. result.m_length = 2;
  443. result.m_blocks[0] = 0x6fc10000;
  444. result.m_blocks[1] = 0x002386f2;
  445. }
  446. else if (i == 2)
  447. {
  448. // 10 ^ 32
  449. // { 4, { 0x00000000, 0x85acef81, 0x2d6d415b, 0x000004ee, } },
  450. result.m_length = 4;
  451. result.m_blocks[0] = 0x00000000;
  452. result.m_blocks[1] = 0x85acef81;
  453. result.m_blocks[2] = 0x2d6d415b;
  454. result.m_blocks[3] = 0x000004ee;
  455. }
  456. else if (i == 3)
  457. {
  458. // 10 ^ 64
  459. // { 7, { 0x00000000, 0x00000000, 0xbf6a1f01, 0x6e38ed64, 0xdaa797ed, 0xe93ff9f4, 0x00184f03, } },
  460. result.m_length = 7;
  461. result.m_blocks[0] = 0x00000000;
  462. result.m_blocks[1] = 0x00000000;
  463. result.m_blocks[2] = 0xbf6a1f01;
  464. result.m_blocks[3] = 0x6e38ed64;
  465. result.m_blocks[4] = 0xdaa797ed;
  466. result.m_blocks[5] = 0xe93ff9f4;
  467. result.m_blocks[6] = 0x00184f03;
  468. }
  469. else if (i == 4)
  470. {
  471. // 10 ^ 128
  472. //{
  473. // 14, {
  474. // 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x2e953e01, 0x03df9909, 0x0f1538fd,
  475. // 0x2374e42f, 0xd3cff5ec, 0xc404dc08, 0xbccdb0da, 0xa6337f19, 0xe91f2603, 0x0000024e, }
  476. //},
  477. result.m_length = 14;
  478. result.m_blocks[0] = 0x00000000;
  479. result.m_blocks[1] = 0x00000000;
  480. result.m_blocks[2] = 0x00000000;
  481. result.m_blocks[3] = 0x00000000;
  482. result.m_blocks[4] = 0x2e953e01;
  483. result.m_blocks[5] = 0x03df9909;
  484. result.m_blocks[6] = 0x0f1538fd;
  485. result.m_blocks[7] = 0x2374e42f;
  486. result.m_blocks[8] = 0xd3cff5ec;
  487. result.m_blocks[9] = 0xc404dc08;
  488. result.m_blocks[10] = 0xbccdb0da;
  489. result.m_blocks[11] = 0xa6337f19;
  490. result.m_blocks[12] = 0xe91f2603;
  491. result.m_blocks[13] = 0x0000024e;
  492. }
  493. else
  494. {
  495. // 10 ^ 256
  496. //{
  497. // 27, {
  498. // 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
  499. // 0x00000000, 0x982e7c01, 0xbed3875b, 0xd8d99f72, 0x12152f87, 0x6bde50c6, 0xcf4a6e70,
  500. // 0xd595d80f, 0x26b2716e, 0xadc666b0, 0x1d153624, 0x3c42d35a, 0x63ff540e, 0xcc5573c0,
  501. // 0x65f9ef17, 0x55bc28f2, 0x80dcc7f7, 0xf46eeddc, 0x5fdcefce, 0x000553f7,
  502. // }
  503. //}
  504. result.m_length = 27;
  505. result.m_blocks[0] = 0x00000000;
  506. result.m_blocks[1] = 0x00000000;
  507. result.m_blocks[2] = 0x00000000;
  508. result.m_blocks[3] = 0x00000000;
  509. result.m_blocks[4] = 0x00000000;
  510. result.m_blocks[5] = 0x00000000;
  511. result.m_blocks[6] = 0x00000000;
  512. result.m_blocks[7] = 0x00000000;
  513. result.m_blocks[8] = 0x982e7c01;
  514. result.m_blocks[9] = 0xbed3875b;
  515. result.m_blocks[10] = 0xd8d99f72;
  516. result.m_blocks[11] = 0x12152f87;
  517. result.m_blocks[12] = 0x6bde50c6;
  518. result.m_blocks[13] = 0xcf4a6e70;
  519. result.m_blocks[14] = 0xd595d80f;
  520. result.m_blocks[15] = 0x26b2716e;
  521. result.m_blocks[16] = 0xadc666b0;
  522. result.m_blocks[17] = 0x1d153624;
  523. result.m_blocks[18] = 0x3c42d35a;
  524. result.m_blocks[19] = 0x63ff540e;
  525. result.m_blocks[20] = 0xcc5573c0;
  526. result.m_blocks[21] = 0x65f9ef17;
  527. result.m_blocks[22] = 0x55bc28f2;
  528. result.m_blocks[23] = 0x80dcc7f7;
  529. result.m_blocks[24] = 0xf46eeddc;
  530. result.m_blocks[25] = 0x5fdcefce;
  531. result.m_blocks[26] = 0x000553f7;
  532. }
  533. return result;
  534. }
  535. //******************************************************************************
  536. // result = 10^exponent
  537. //******************************************************************************
  538. private static void BigInt_Pow10(out tBigInt pResult, uint exponent)
  539. {
  540. // make sure the exponent is within the bounds of the lookup table data
  541. // RJ_ASSERT(exponent < 512);
  542. // create two temporary values to reduce large integer copy operations
  543. tBigInt temp1 = default;
  544. tBigInt temp2 = default;
  545. ref tBigInt pCurTemp = ref temp1;
  546. ref tBigInt pNextTemp = ref temp2;
  547. // initialize the result by looking up a 32-bit power of 10 corresponding to the first 3 bits
  548. uint smallExponent = exponent & 0x7;
  549. pCurTemp.SetU32(g_PowerOf10_U32[smallExponent]);
  550. // remove the low bits that we used for the 32-bit lookup table
  551. exponent >>= 3;
  552. int tableIdx = 0;
  553. // while there are remaining bits in the exponent to be processed
  554. while (exponent != 0)
  555. {
  556. // if the current bit is set, multiply it with the corresponding power of 10
  557. if ((exponent & 1) != 0)
  558. {
  559. // multiply into the next temporary
  560. BigInt_Multiply(out pNextTemp, pCurTemp, g_PowerOf10_Big(tableIdx));
  561. // swap to the next temporary
  562. ref tBigInt pSwap = ref pCurTemp;
  563. pCurTemp = pNextTemp;
  564. pNextTemp = pSwap;
  565. }
  566. // advance to the next bit
  567. ++tableIdx;
  568. exponent >>= 1;
  569. }
  570. // output the result
  571. pResult = pCurTemp;
  572. }
  573. //******************************************************************************
  574. // result = in * 10^exponent
  575. //******************************************************************************
  576. private static unsafe void BigInt_MultiplyPow10(out tBigInt pResult, in tBigInt input, uint exponent)
  577. {
  578. // make sure the exponent is within the bounds of the lookup table data
  579. // RJ_ASSERT(exponent < 512);
  580. // create two temporary values to reduce large integer copy operations
  581. tBigInt temp1 = default;
  582. tBigInt temp2 = default;
  583. ref tBigInt pCurTemp = ref temp1;
  584. ref tBigInt pNextTemp = ref temp2;
  585. // initialize the result by looking up a 32-bit power of 10 corresponding to the first 3 bits
  586. uint smallExponent = exponent & 0x7;
  587. if (smallExponent != 0)
  588. {
  589. BigInt_Multiply(out pCurTemp, input, g_PowerOf10_U32[smallExponent]);
  590. }
  591. else
  592. {
  593. pCurTemp = input;
  594. }
  595. // remove the low bits that we used for the 32-bit lookup table
  596. exponent >>= 3;
  597. int tableIdx = 0;
  598. // while there are remaining bits in the exponent to be processed
  599. while (exponent != 0)
  600. {
  601. // if the current bit is set, multiply it with the corresponding power of 10
  602. if((exponent & 1) != 0)
  603. {
  604. // multiply into the next temporary
  605. BigInt_Multiply( out pNextTemp, pCurTemp, g_PowerOf10_Big(tableIdx) );
  606. // swap to the next temporary
  607. ref tBigInt pSwap = ref pCurTemp;
  608. pCurTemp = pNextTemp;
  609. pNextTemp = pSwap;
  610. }
  611. // advance to the next bit
  612. ++tableIdx;
  613. exponent >>= 1;
  614. }
  615. // output the result
  616. pResult = pCurTemp;
  617. }
  618. //******************************************************************************
  619. // result = 2^exponent
  620. //******************************************************************************
  621. private static unsafe void BigInt_Pow2(out tBigInt pResult, uint exponent)
  622. {
  623. int blockIdx = (int)exponent / 32;
  624. //RJ_ASSERT(blockIdx < c_BigInt_MaxBlocks);
  625. for (uint i = 0; i <= blockIdx; ++i)
  626. pResult.m_blocks[i] = 0;
  627. pResult.m_length = blockIdx + 1;
  628. int bitIdx = ((int)exponent % 32);
  629. pResult.m_blocks[blockIdx] |= (uint)(1 << bitIdx);
  630. }
  631. //******************************************************************************
  632. // This function will divide two large numbers under the assumption that the
  633. // result is within the range [0,10) and the input numbers have been shifted
  634. // to satisfy:
  635. // - The highest block of the divisor is greater than or equal to 8 such that
  636. // there is enough precision to make an accurate first guess at the quotient.
  637. // - The highest block of the divisor is less than the maximum value on an
  638. // unsigned 32-bit integer such that we can safely increment without overflow.
  639. // - The dividend does not contain more blocks than the divisor such that we
  640. // can estimate the quotient by dividing the equivalently placed high blocks.
  641. //
  642. // quotient = floor(dividend / divisor)
  643. // remainder = dividend - quotient*divisor
  644. //
  645. // pDividend is updated to be the remainder and the quotient is returned.
  646. //******************************************************************************
  647. private static unsafe uint BigInt_DivideWithRemainder_MaxQuotient9(ref tBigInt pDividend, in tBigInt divisor)
  648. {
  649. // Check that the divisor has been correctly shifted into range and that it is not
  650. // smaller than the dividend in length.
  651. //RJ_ASSERT( !divisor.IsZero() &&
  652. // divisor.m_blocks[divisor.m_length-1] >= 8 &&
  653. // divisor.m_blocks[divisor.m_length-1] < 0xFFFFFFFF &&
  654. // pDividend->m_length <= divisor.m_length );
  655. // If the dividend is smaller than the divisor, the quotient is zero and the divisor is already
  656. // the remainder.
  657. int length = divisor.m_length;
  658. if (pDividend.m_length < divisor.m_length)
  659. return 0;
  660. fixed (uint* pDivisorCur1 = divisor.m_blocks)
  661. fixed (uint* pDividendCur1 = pDividend.m_blocks)
  662. {
  663. uint* pDivisorCur = pDivisorCur1;
  664. uint* pDividendCur = pDividendCur1;
  665. uint* pFinalDivisorBlock = pDivisorCur + length - 1;
  666. uint* pFinalDividendBlock = pDividendCur + length - 1;
  667. // Compute an estimated quotient based on the high block value. This will either match the actual quotient or
  668. // undershoot by one.
  669. uint quotient = *pFinalDividendBlock / (*pFinalDivisorBlock + 1);
  670. //RJ_ASSERT(quotient <= 9);
  671. // Divide out the estimated quotient
  672. if (quotient != 0)
  673. {
  674. // dividend = dividend - divisor*quotient
  675. ulong borrow = 0;
  676. ulong carry = 0;
  677. do
  678. {
  679. ulong product = (ulong) *pDivisorCur * (ulong) quotient + carry;
  680. carry = product >> 32;
  681. ulong difference = (ulong) *pDividendCur - (product & 0xFFFFFFFF) - borrow;
  682. borrow = (difference >> 32) & 1;
  683. *pDividendCur = (uint) (difference & 0xFFFFFFFF);
  684. ++pDivisorCur;
  685. ++pDividendCur;
  686. } while (pDivisorCur <= pFinalDivisorBlock);
  687. // remove all leading zero blocks from dividend
  688. while (length > 0 && pDividend.m_blocks[length - 1] == 0)
  689. --length;
  690. pDividend.m_length = length;
  691. }
  692. // If the dividend is still larger than the divisor, we overshot our estimate quotient. To correct,
  693. // we increment the quotient and subtract one more divisor from the dividend.
  694. if (BigInt_Compare(pDividend, divisor) >= 0)
  695. {
  696. ++quotient;
  697. // dividend = dividend - divisor
  698. pDivisorCur = pDivisorCur1;
  699. pDividendCur = pDividendCur1;
  700. ulong borrow = 0;
  701. do
  702. {
  703. ulong difference = (ulong) *pDividendCur - (ulong) *pDivisorCur - borrow;
  704. borrow = (difference >> 32) & 1;
  705. *pDividendCur = (uint)(difference & 0xFFFFFFFF);
  706. ++pDivisorCur;
  707. ++pDividendCur;
  708. } while (pDivisorCur <= pFinalDivisorBlock);
  709. // remove all leading zero blocks from dividend
  710. while (length > 0 && pDividend.m_blocks[length - 1] == 0)
  711. --length;
  712. pDividend.m_length = length;
  713. }
  714. return quotient;
  715. }
  716. }
  717. //******************************************************************************
  718. // result = result << shift
  719. //******************************************************************************
  720. private static unsafe void BigInt_ShiftLeft(ref tBigInt pResult, uint shift)
  721. {
  722. // RJ_ASSERT( shift != 0 );
  723. int shiftBlocks = (int)shift / 32;
  724. int shiftBits = (int)shift % 32;
  725. int inLength = pResult.m_length;
  726. // RJ_ASSERT( inLength + shiftBlocks <= c_BigInt_MaxBlocks );
  727. // check if the shift is block aligned
  728. if (shiftBits == 0)
  729. {
  730. // process blocks high to low so that we can safely process in place
  731. fixed (uint* pInBlocks1 = pResult.m_blocks)
  732. {
  733. uint* pInBlocks = pInBlocks1;
  734. uint* pInCur = pInBlocks + inLength - 1;
  735. uint* pOutCur = pInCur + shiftBlocks;
  736. // copy blocks from high to low
  737. for (; pInCur >= pInBlocks; --pInCur, --pOutCur)
  738. {
  739. *pOutCur = *pInCur;
  740. }
  741. }
  742. // zero the remaining low blocks
  743. for ( uint i = 0; i < shiftBlocks; ++i)
  744. pResult.m_blocks[i] = 0;
  745. pResult.m_length += shiftBlocks;
  746. }
  747. // else we need to shift partial blocks
  748. else
  749. {
  750. int inBlockIdx = inLength - 1;
  751. int outBlockIdx = inLength + shiftBlocks;
  752. // set the length to hold the shifted blocks
  753. //RJ_ASSERT( outBlockIdx < c_BigInt_MaxBlocks );
  754. pResult.m_length = outBlockIdx + 1;
  755. // output the initial blocks
  756. int lowBitsShift = (32 - shiftBits);
  757. uint highBits = 0;
  758. uint block = pResult.m_blocks[inBlockIdx];
  759. uint lowBits = block >> lowBitsShift;
  760. while ( inBlockIdx > 0 )
  761. {
  762. pResult.m_blocks[outBlockIdx] = highBits | lowBits;
  763. highBits = block << shiftBits;
  764. --inBlockIdx;
  765. --outBlockIdx;
  766. block = pResult.m_blocks[inBlockIdx];
  767. lowBits = block >> lowBitsShift;
  768. }
  769. // output the final blocks
  770. // RJ_ASSERT( outBlockIdx == shiftBlocks + 1 );
  771. pResult.m_blocks[outBlockIdx] = highBits | lowBits;
  772. pResult.m_blocks[outBlockIdx-1] = block << shiftBits;
  773. // zero the remaining low blocks
  774. for ( uint i = 0; i < shiftBlocks; ++i)
  775. pResult.m_blocks[i] = 0;
  776. // check if the terminating block has no set bits
  777. if (pResult.m_blocks[pResult.m_length - 1] == 0)
  778. --pResult.m_length;
  779. }
  780. }
  781. //******************************************************************************
  782. // Different modes for terminating digit output
  783. //******************************************************************************
  784. public enum CutoffMode
  785. {
  786. Unique, // as many digits as necessary to print a uniquely identifiable number
  787. TotalLength, // up to cutoffNumber significant digits
  788. FractionLength, // up to cutoffNumber significant digits past the decimal point
  789. };
  790. //******************************************************************************
  791. // This is an implementation the Dragon4 algorithm to convert a binary number
  792. // in floating point format to a decimal number in string format. The function
  793. // returns the number of digits written to the output buffer and the output is
  794. // not NUL terminated.
  795. //
  796. // The floating point input value is (mantissa * 2^exponent).
  797. //
  798. // See the following papers for more information on the algorithm:
  799. // "How to Print Floating-Point Numbers Accurately"
  800. // Steele and White
  801. // http://kurtstephens.com/files/p372-steele.pdf
  802. // "Printing Floating-Point Numbers Quickly and Accurately"
  803. // Burger and Dybvig
  804. // http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.72.4656&rep=rep1&type=pdf
  805. //******************************************************************************
  806. private static unsafe uint Dragon4
  807. (
  808. ulong mantissa, // value significand
  809. int exponent, // value exponent in base 2
  810. uint mantissaHighBitIdx, // index of the highest set mantissa bit
  811. bool hasUnequalMargins, // is the high margin twice as large as the low margin
  812. CutoffMode cutoffMode, // how to determine output length
  813. uint cutoffNumber, // parameter to the selected cutoffMode
  814. byte* pOutBuffer, // buffer to output into
  815. uint bufferSize, // maximum characters that can be printed to pOutBuffer
  816. out int pOutExponent // the base 10 exponent of the first digit
  817. )
  818. {
  819. byte* pCurDigit = pOutBuffer;
  820. // RJ_ASSERT( bufferSize > 0 );
  821. // if the mantissa is zero, the value is zero regardless of the exponent
  822. if (mantissa == 0)
  823. {
  824. *pCurDigit = (byte)'0';
  825. pOutExponent = 0;
  826. return 1;
  827. }
  828. // compute the initial state in integral form such that
  829. // value = scaledValue / scale
  830. // marginLow = scaledMarginLow / scale
  831. tBigInt scale = default; // positive scale applied to value and margin such that they can be
  832. // represented as whole numbers
  833. tBigInt scaledValue = default; // scale * mantissa
  834. tBigInt scaledMarginLow = default; // scale * 0.5 * (distance between this floating-point number and its
  835. // immediate lower value)
  836. // For normalized IEEE floating point values, each time the exponent is incremented the margin also
  837. // doubles. That creates a subset of transition numbers where the high margin is twice the size of
  838. // the low margin.
  839. tBigInt * pScaledMarginHigh;
  840. tBigInt optionalMarginHigh = default;
  841. if ( hasUnequalMargins )
  842. {
  843. // if we have no fractional component
  844. if (exponent > 0)
  845. {
  846. // 1) Expand the input value by multiplying out the mantissa and exponent. This represents
  847. // the input value in its whole number representation.
  848. // 2) Apply an additional scale of 2 such that later comparisons against the margin values
  849. // are simplified.
  850. // 3) Set the margin value to the lowest mantissa bit's scale.
  851. // scaledValue = 2 * 2 * mantissa*2^exponent
  852. scaledValue.SetU64( 4 * mantissa );
  853. BigInt_ShiftLeft(ref scaledValue, (uint)exponent);
  854. // scale = 2 * 2 * 1
  855. scale.SetU32( 4 );
  856. // scaledMarginLow = 2 * 2^(exponent-1)
  857. BigInt_Pow2( out scaledMarginLow, (uint)exponent );
  858. // scaledMarginHigh = 2 * 2 * 2^(exponent-1)
  859. BigInt_Pow2( out optionalMarginHigh, (uint)(exponent + 1));
  860. }
  861. // else we have a fractional exponent
  862. else
  863. {
  864. // In order to track the mantissa data as an integer, we store it as is with a large scale
  865. // scaledValue = 2 * 2 * mantissa
  866. scaledValue.SetU64( 4 * mantissa );
  867. // scale = 2 * 2 * 2^(-exponent)
  868. BigInt_Pow2(out scale, (uint)(-exponent + 2));
  869. // scaledMarginLow = 2 * 2^(-1)
  870. scaledMarginLow.SetU32( 1 );
  871. // scaledMarginHigh = 2 * 2 * 2^(-1)
  872. optionalMarginHigh.SetU32( 2 );
  873. }
  874. // the high and low margins are different
  875. pScaledMarginHigh = &optionalMarginHigh;
  876. }
  877. else
  878. {
  879. // if we have no fractional component
  880. if (exponent > 0)
  881. {
  882. // 1) Expand the input value by multiplying out the mantissa and exponent. This represents
  883. // the input value in its whole number representation.
  884. // 2) Apply an additional scale of 2 such that later comparisons against the margin values
  885. // are simplified.
  886. // 3) Set the margin value to the lowest mantissa bit's scale.
  887. // scaledValue = 2 * mantissa*2^exponent
  888. scaledValue.SetU64( 2 * mantissa );
  889. BigInt_ShiftLeft(ref scaledValue, (uint)exponent);
  890. // scale = 2 * 1
  891. scale.SetU32( 2 );
  892. // scaledMarginLow = 2 * 2^(exponent-1)
  893. BigInt_Pow2(out scaledMarginLow, (uint)exponent );
  894. }
  895. // else we have a fractional exponent
  896. else
  897. {
  898. // In order to track the mantissa data as an integer, we store it as is with a large scale
  899. // scaledValue = 2 * mantissa
  900. scaledValue.SetU64( 2 * mantissa );
  901. // scale = 2 * 2^(-exponent)
  902. BigInt_Pow2(out scale, (uint)(-exponent + 1));
  903. // scaledMarginLow = 2 * 2^(-1)
  904. scaledMarginLow.SetU32( 1 );
  905. }
  906. // the high and low margins are equal
  907. pScaledMarginHigh = &scaledMarginLow;
  908. }
  909. // Compute an estimate for digitExponent that will be correct or undershoot by one.
  910. // This optimization is based on the paper "Printing Floating-Point Numbers Quickly and Accurately"
  911. // by Burger and Dybvig http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.72.4656&rep=rep1&type=pdf
  912. // We perform an additional subtraction of 0.69 to increase the frequency of a failed estimate
  913. // because that lets us take a faster branch in the code. 0.69 is chosen because 0.69 + log10(2) is
  914. // less than one by a reasonable epsilon that will account for any floating point error.
  915. //
  916. // We want to set digitExponent to floor(log10(v)) + 1
  917. // v = mantissa*2^exponent
  918. // log2(v) = log2(mantissa) + exponent;
  919. // log10(v) = log2(v) * log10(2)
  920. // floor(log2(v)) = mantissaHighBitIdx + exponent;
  921. // log10(v) - log10(2) < (mantissaHighBitIdx + exponent) * log10(2) <= log10(v)
  922. // log10(v) < (mantissaHighBitIdx + exponent) * log10(2) + log10(2) <= log10(v) + log10(2)
  923. // floor( log10(v) ) < ceil( (mantissaHighBitIdx + exponent) * log10(2) ) <= floor( log10(v) ) + 1
  924. const double log10_2 = 0.30102999566398119521373889472449;
  925. var digitExponentDoubleValue = (double) ((int) mantissaHighBitIdx + exponent) * log10_2 - 0.69;
  926. digitExponentDoubleValue = Math.Ceiling(digitExponentDoubleValue);
  927. int digitExponent = (int)digitExponentDoubleValue;
  928. // if the digit exponent is smaller than the smallest desired digit for fractional cutoff,
  929. // pull the digit back into legal range at which point we will round to the appropriate value.
  930. // Note that while our value for digitExponent is still an estimate, this is safe because it
  931. // only increases the number. This will either correct digitExponent to an accurate value or it
  932. // will clamp it above the accurate value.
  933. if (cutoffMode == CutoffMode.FractionLength && digitExponent <= -(int)cutoffNumber)
  934. {
  935. digitExponent = -(int)cutoffNumber + 1;
  936. }
  937. // Divide value by 10^digitExponent.
  938. if (digitExponent > 0)
  939. {
  940. // The exponent is positive creating a division so we multiply up the scale.
  941. tBigInt temp;
  942. BigInt_MultiplyPow10( out temp, scale, (uint)digitExponent );
  943. scale = temp;
  944. }
  945. else if (digitExponent < 0)
  946. {
  947. // The exponent is negative creating a multiplication so we multiply up the scaledValue,
  948. // scaledMarginLow and scaledMarginHigh.
  949. tBigInt pow10;
  950. BigInt_Pow10(out pow10, (uint)(-digitExponent));
  951. tBigInt temp;
  952. BigInt_Multiply( out temp, scaledValue, pow10);
  953. scaledValue = temp;
  954. BigInt_Multiply( out temp, scaledMarginLow, pow10);
  955. scaledMarginLow = temp;
  956. if (pScaledMarginHigh != &scaledMarginLow)
  957. BigInt_Multiply2( out *pScaledMarginHigh, scaledMarginLow );
  958. }
  959. // If (value >= 1), our estimate for digitExponent was too low
  960. if( BigInt_Compare(scaledValue,scale) >= 0 )
  961. {
  962. // The exponent estimate was incorrect.
  963. // Increment the exponent and don't perform the premultiply needed
  964. // for the first loop iteration.
  965. digitExponent = digitExponent + 1;
  966. }
  967. else
  968. {
  969. // The exponent estimate was correct.
  970. // Multiply larger by the output base to prepare for the first loop iteration.
  971. BigInt_Multiply10( ref scaledValue );
  972. BigInt_Multiply10( ref scaledMarginLow );
  973. if (pScaledMarginHigh != &scaledMarginLow)
  974. BigInt_Multiply2( out *pScaledMarginHigh, scaledMarginLow );
  975. }
  976. // Compute the cutoff exponent (the exponent of the final digit to print).
  977. // Default to the maximum size of the output buffer.
  978. int cutoffExponent = digitExponent - (int)bufferSize;
  979. switch (cutoffMode)
  980. {
  981. // print digits until we pass the accuracy margin limits or buffer size
  982. case CutoffMode.Unique:
  983. break;
  984. // print cutoffNumber of digits or until we reach the buffer size
  985. case CutoffMode.TotalLength:
  986. {
  987. int desiredCutoffExponent = digitExponent - (int) cutoffNumber;
  988. if (desiredCutoffExponent > cutoffExponent)
  989. cutoffExponent = desiredCutoffExponent;
  990. }
  991. break;
  992. // print cutoffNumber digits past the decimal point or until we reach the buffer size
  993. case CutoffMode.FractionLength:
  994. {
  995. int desiredCutoffExponent = -(int) cutoffNumber;
  996. if (desiredCutoffExponent > cutoffExponent)
  997. cutoffExponent = desiredCutoffExponent;
  998. }
  999. break;
  1000. }
  1001. // Output the exponent of the first digit we will print
  1002. pOutExponent = digitExponent-1;
  1003. // In preparation for calling BigInt_DivideWithRemainder_MaxQuotient9(),
  1004. // we need to scale up our values such that the highest block of the denominator
  1005. // is greater than or equal to 8. We also need to guarantee that the numerator
  1006. // can never have a length greater than the denominator after each loop iteration.
  1007. // This requires the highest block of the denominator to be less than or equal to
  1008. // 429496729 which is the highest number that can be multiplied by 10 without
  1009. // overflowing to a new block.
  1010. // RJ_ASSERT( scale.GetLength() > 0 );
  1011. uint hiBlock = scale.GetBlock( scale.GetLength() - 1 );
  1012. if (hiBlock < 8 || hiBlock > 429496729)
  1013. {
  1014. // Perform a bit shift on all values to get the highest block of the denominator into
  1015. // the range [8,429496729]. We are more likely to make accurate quotient estimations
  1016. // in BigInt_DivideWithRemainder_MaxQuotient9() with higher denominator values so
  1017. // we shift the denominator to place the highest bit at index 27 of the highest block.
  1018. // This is safe because (2^28 - 1) = 268435455 which is less than 429496729. This means
  1019. // that all values with a highest bit at index 27 are within range.
  1020. uint hiBlockLog2 = LogBase2(hiBlock);
  1021. // RJ_ASSERT(hiBlockLog2 < 3 || hiBlockLog2 > 27);
  1022. uint shift = (32 + 27 - hiBlockLog2) % 32;
  1023. BigInt_ShiftLeft( ref scale, shift );
  1024. BigInt_ShiftLeft( ref scaledValue, shift);
  1025. BigInt_ShiftLeft( ref scaledMarginLow, shift);
  1026. if (pScaledMarginHigh != &scaledMarginLow)
  1027. BigInt_Multiply2( out *pScaledMarginHigh, scaledMarginLow );
  1028. }
  1029. // These values are used to inspect why the print loop terminated so we can properly
  1030. // round the final digit.
  1031. bool low; // did the value get within marginLow distance from zero
  1032. bool high; // did the value get within marginHigh distance from one
  1033. uint outputDigit; // current digit being output
  1034. if (cutoffMode == CutoffMode.Unique)
  1035. {
  1036. // For the unique cutoff mode, we will try to print until we have reached a level of
  1037. // precision that uniquely distinguishes this value from its neighbors. If we run
  1038. // out of space in the output buffer, we terminate early.
  1039. for (;;)
  1040. {
  1041. digitExponent = digitExponent-1;
  1042. // divide out the scale to extract the digit
  1043. outputDigit = BigInt_DivideWithRemainder_MaxQuotient9(ref scaledValue, scale);
  1044. //RJ_ASSERT( outputDigit < 10 );
  1045. // update the high end of the value
  1046. tBigInt scaledValueHigh;
  1047. BigInt_Add( out scaledValueHigh, scaledValue, *pScaledMarginHigh );
  1048. // stop looping if we are far enough away from our neighboring values
  1049. // or if we have reached the cutoff digit
  1050. low = BigInt_Compare(scaledValue, scaledMarginLow) < 0;
  1051. high = BigInt_Compare(scaledValueHigh, scale) > 0;
  1052. if (low | high | (digitExponent == cutoffExponent))
  1053. break;
  1054. // store the output digit
  1055. *pCurDigit = (byte)('0' + outputDigit);
  1056. ++pCurDigit;
  1057. // multiply larger by the output base
  1058. BigInt_Multiply10( ref scaledValue );
  1059. BigInt_Multiply10( ref scaledMarginLow );
  1060. if (pScaledMarginHigh != &scaledMarginLow)
  1061. BigInt_Multiply2( out *pScaledMarginHigh, scaledMarginLow );
  1062. }
  1063. }
  1064. else
  1065. {
  1066. // For length based cutoff modes, we will try to print until we
  1067. // have exhausted all precision (i.e. all remaining digits are zeros) or
  1068. // until we reach the desired cutoff digit.
  1069. low = false;
  1070. high = false;
  1071. for (;;)
  1072. {
  1073. digitExponent = digitExponent-1;
  1074. // divide out the scale to extract the digit
  1075. outputDigit = BigInt_DivideWithRemainder_MaxQuotient9(ref scaledValue, scale);
  1076. //RJ_ASSERT( outputDigit < 10 );
  1077. if ( scaledValue.IsZero() | (digitExponent == cutoffExponent) )
  1078. break;
  1079. // store the output digit
  1080. *pCurDigit = (byte)('0' + outputDigit);
  1081. ++pCurDigit;
  1082. // multiply larger by the output base
  1083. BigInt_Multiply10(ref scaledValue);
  1084. }
  1085. }
  1086. // round off the final digit
  1087. // default to rounding down if value got too close to 0
  1088. bool roundDown = low;
  1089. // if it is legal to round up and down
  1090. if (low == high)
  1091. {
  1092. // round to the closest digit by comparing value with 0.5. To do this we need to convert
  1093. // the inequality to large integer values.
  1094. // compare( value, 0.5 )
  1095. // compare( scale * value, scale * 0.5 )
  1096. // compare( 2 * scale * value, scale )
  1097. BigInt_Multiply2(ref scaledValue);
  1098. int compare = BigInt_Compare(scaledValue, scale);
  1099. roundDown = compare < 0;
  1100. // if we are directly in the middle, round towards the even digit (i.e. IEEE rouding rules)
  1101. if (compare == 0)
  1102. roundDown = (outputDigit & 1) == 0;
  1103. }
  1104. // print the rounded digit
  1105. if (roundDown)
  1106. {
  1107. *pCurDigit = (byte)('0' + outputDigit);
  1108. ++pCurDigit;
  1109. }
  1110. else
  1111. {
  1112. // handle rounding up
  1113. if (outputDigit == 9)
  1114. {
  1115. // find the first non-nine prior digit
  1116. for (;;)
  1117. {
  1118. // if we are at the first digit
  1119. if (pCurDigit == pOutBuffer)
  1120. {
  1121. // output 1 at the next highest exponent
  1122. *pCurDigit = (byte)'1';
  1123. ++pCurDigit;
  1124. pOutExponent += 1;
  1125. break;
  1126. }
  1127. --pCurDigit;
  1128. if (*pCurDigit != (byte)'9')
  1129. {
  1130. // increment the digit
  1131. *pCurDigit += 1;
  1132. ++pCurDigit;
  1133. break;
  1134. }
  1135. }
  1136. }
  1137. else
  1138. {
  1139. // values in the range [0,8] can perform a simple round up
  1140. *pCurDigit = (byte)((byte)'0' + outputDigit + 1);
  1141. ++pCurDigit;
  1142. }
  1143. }
  1144. // return the number of digits output
  1145. uint outputLen = (uint)(pCurDigit - pOutBuffer);
  1146. // RJ_ASSERT(outputLen <= bufferSize);
  1147. return outputLen;
  1148. }
  1149. //******************************************************************************
  1150. //******************************************************************************
  1151. public enum PrintFloatFormat
  1152. {
  1153. Positional, // [-]ddddd.dddd
  1154. Scientific, // [-]d.dddde[sign]ddd
  1155. }
  1156. //******************************************************************************\
  1157. // Helper union to decompose a 32-bit IEEE float.
  1158. // sign: 1 bit
  1159. // exponent: 8 bits
  1160. // mantissa: 23 bits
  1161. //******************************************************************************
  1162. [StructLayout(LayoutKind.Explicit)]
  1163. public struct tFloatUnion32
  1164. {
  1165. public bool IsNegative() { return (m_integer >> 31) != 0; }
  1166. public uint GetExponent() { return (m_integer >> 23) & 0xFF; }
  1167. public uint GetMantissa() { return m_integer & 0x7FFFFF; }
  1168. [FieldOffset(0)]
  1169. public float m_floatingPoint;
  1170. [FieldOffset(0)]
  1171. public uint m_integer;
  1172. };
  1173. //******************************************************************************
  1174. // Helper union to decompose a 64-bit IEEE float.
  1175. // sign: 1 bit
  1176. // exponent: 11 bits
  1177. // mantissa: 52 bits
  1178. //******************************************************************************
  1179. [StructLayout(LayoutKind.Explicit)]
  1180. public struct tFloatUnion64
  1181. {
  1182. public bool IsNegative() { return (m_integer >> 63) != 0; }
  1183. public uint GetExponent() { return (uint)((m_integer >> 52) & 0x7FF); }
  1184. public ulong GetMantissa() { return m_integer & 0xFFFFFFFFFFFFFUL; }
  1185. [FieldOffset(0)]
  1186. public double m_floatingPoint;
  1187. [FieldOffset(0)]
  1188. public ulong m_integer;
  1189. };
  1190. //******************************************************************************
  1191. // Outputs the positive number with positional notation: ddddd.dddd
  1192. // The output is always NUL terminated and the output length (not including the
  1193. // NUL) is returned.
  1194. //******************************************************************************
  1195. private static unsafe int FormatPositional
  1196. (
  1197. byte* pOutBuffer, // buffer to output into
  1198. uint bufferSize, // maximum characters that can be printed to pOutBuffer
  1199. ulong mantissa, // value significand
  1200. int exponent, // value exponent in base 2
  1201. uint mantissaHighBitIdx, // index of the highest set mantissa bit
  1202. bool hasUnequalMargins, // is the high margin twice as large as the low margin
  1203. int precision // Negative prints as many digits as are needed for a unique
  1204. // number. Positive specifies the maximum number of
  1205. // significant digits to print past the decimal point.
  1206. )
  1207. {
  1208. //RJ_ASSERT(bufferSize > 0);
  1209. int printExponent;
  1210. uint numPrintDigits;
  1211. uint maxPrintLen = bufferSize - 1;
  1212. if (precision < 0)
  1213. {
  1214. numPrintDigits = Dragon4(mantissa,
  1215. exponent,
  1216. mantissaHighBitIdx,
  1217. hasUnequalMargins,
  1218. CutoffMode.Unique,
  1219. 0,
  1220. pOutBuffer,
  1221. maxPrintLen,
  1222. out printExponent);
  1223. }
  1224. else
  1225. {
  1226. numPrintDigits = Dragon4(mantissa,
  1227. exponent,
  1228. mantissaHighBitIdx,
  1229. hasUnequalMargins,
  1230. CutoffMode.FractionLength,
  1231. (uint)precision,
  1232. pOutBuffer,
  1233. maxPrintLen,
  1234. out printExponent);
  1235. }
  1236. //RJ_ASSERT(numPrintDigits > 0);
  1237. //RJ_ASSERT(numPrintDigits <= bufferSize);
  1238. // track the number of digits past the decimal point that have been printed
  1239. uint numFractionDigits = 0;
  1240. // if output has a whole number
  1241. if (printExponent >= 0)
  1242. {
  1243. // leave the whole number at the start of the buffer
  1244. uint numWholeDigits = (uint)(printExponent + 1);
  1245. if (numPrintDigits < numWholeDigits)
  1246. {
  1247. // don't overflow the buffer
  1248. if (numWholeDigits > maxPrintLen)
  1249. numWholeDigits = maxPrintLen;
  1250. // add trailing zeros up to the decimal point
  1251. for (; numPrintDigits < numWholeDigits; ++numPrintDigits)
  1252. pOutBuffer[numPrintDigits] = (byte)'0';
  1253. }
  1254. // insert the decimal point prior to the fraction
  1255. else if (numPrintDigits > (uint)numWholeDigits)
  1256. {
  1257. numFractionDigits = numPrintDigits - numWholeDigits;
  1258. uint maxFractionDigits = maxPrintLen - numWholeDigits - 1;
  1259. if (numFractionDigits > maxFractionDigits)
  1260. numFractionDigits = maxFractionDigits;
  1261. Unsafe.CopyBlock(pOutBuffer + numWholeDigits + 1, pOutBuffer + numWholeDigits, numFractionDigits);
  1262. pOutBuffer[numWholeDigits] = (byte)'.';
  1263. numPrintDigits = numWholeDigits + 1 + numFractionDigits;
  1264. }
  1265. }
  1266. else
  1267. {
  1268. // shift out the fraction to make room for the leading zeros
  1269. if (maxPrintLen > 2)
  1270. {
  1271. uint numFractionZeros = (uint)( - printExponent - 1);
  1272. uint maxFractionZeros = maxPrintLen - 2;
  1273. if (numFractionZeros > maxFractionZeros)
  1274. numFractionZeros = maxFractionZeros;
  1275. uint digitsStartIdx = 2 + numFractionZeros;
  1276. // shift the significant digits right such that there is room for leading zeros
  1277. numFractionDigits = numPrintDigits;
  1278. uint maxFractionDigits = maxPrintLen - digitsStartIdx;
  1279. if (numFractionDigits > maxFractionDigits)
  1280. numFractionDigits = maxFractionDigits;
  1281. Unsafe.CopyBlock(pOutBuffer + digitsStartIdx, pOutBuffer, numFractionDigits);
  1282. // insert the leading zeros
  1283. for (uint i = 2; i < digitsStartIdx; ++i)
  1284. pOutBuffer[i] = (byte)'0';
  1285. // update the counts
  1286. numFractionDigits += numFractionZeros;
  1287. numPrintDigits = numFractionDigits;
  1288. }
  1289. // add the decimal point
  1290. if (maxPrintLen > 1)
  1291. {
  1292. pOutBuffer[1] = (byte)'.';
  1293. numPrintDigits += 1;
  1294. }
  1295. // add the initial zero
  1296. if (maxPrintLen > 0)
  1297. {
  1298. pOutBuffer[0] = (byte)'0';
  1299. numPrintDigits += 1;
  1300. }
  1301. }
  1302. // add trailing zeros up to precision length
  1303. if (precision > (int)numFractionDigits && numPrintDigits < maxPrintLen)
  1304. {
  1305. // add a decimal point if this is the first fractional digit we are printing
  1306. if (numFractionDigits == 0)
  1307. {
  1308. pOutBuffer[numPrintDigits++] = (byte)'.';
  1309. }
  1310. // compute the number of trailing zeros needed
  1311. uint totalDigits = (uint)(numPrintDigits + (precision - (int)numFractionDigits));
  1312. if (totalDigits > maxPrintLen)
  1313. totalDigits = maxPrintLen;
  1314. for (; numPrintDigits < totalDigits; ++numPrintDigits)
  1315. pOutBuffer[numPrintDigits] = (byte)'0';
  1316. }
  1317. // terminate the buffer
  1318. //RJ_ASSERT(numPrintDigits <= maxPrintLen);
  1319. //pOutBuffer[numPrintDigits] = '\0';
  1320. return (int)numPrintDigits;
  1321. }
  1322. //******************************************************************************
  1323. // Outputs the positive number with scientific notation: d.dddde[sign]ddd
  1324. // The output is always NUL terminated and the output length (not including the
  1325. // NUL) is returned.
  1326. //******************************************************************************
  1327. private static unsafe int FormatScientific
  1328. (
  1329. byte* pOutBuffer, // buffer to output into
  1330. uint bufferSize, // maximum characters that can be printed to pOutBuffer
  1331. ulong mantissa, // value significand
  1332. int exponent, // value exponent in base 2
  1333. uint mantissaHighBitIdx, // index of the highest set mantissa bit
  1334. bool hasUnequalMargins, // is the high margin twice as large as the low margin
  1335. int precision // Negative prints as many digits as are needed for a unique
  1336. // number. Positive specifies the maximum number of
  1337. // significant digits to print past the decimal point.
  1338. )
  1339. {
  1340. //RJ_ASSERT(bufferSize > 0);
  1341. int printExponent;
  1342. uint numPrintDigits;
  1343. if (precision < 0)
  1344. {
  1345. numPrintDigits = Dragon4(mantissa,
  1346. exponent,
  1347. mantissaHighBitIdx,
  1348. hasUnequalMargins,
  1349. CutoffMode.Unique,
  1350. 0,
  1351. pOutBuffer,
  1352. bufferSize,
  1353. out printExponent);
  1354. }
  1355. else
  1356. {
  1357. numPrintDigits = Dragon4(mantissa,
  1358. exponent,
  1359. mantissaHighBitIdx,
  1360. hasUnequalMargins,
  1361. CutoffMode.TotalLength,
  1362. (uint)(precision + 1),
  1363. pOutBuffer,
  1364. bufferSize,
  1365. out printExponent);
  1366. }
  1367. //RJ_ASSERT(numPrintDigits > 0);
  1368. //RJ_ASSERT(numPrintDigits <= bufferSize);
  1369. byte* pCurOut = pOutBuffer;
  1370. // keep the whole number as the first digit
  1371. if (bufferSize > 1)
  1372. {
  1373. pCurOut += 1;
  1374. bufferSize -= 1;
  1375. }
  1376. // insert the decimal point prior to the fractional number
  1377. uint numFractionDigits = numPrintDigits - 1;
  1378. if (numFractionDigits > 0 && bufferSize > 1)
  1379. {
  1380. uint maxFractionDigits = bufferSize - 2;
  1381. if (numFractionDigits > maxFractionDigits)
  1382. numFractionDigits = maxFractionDigits;
  1383. Unsafe.CopyBlock(pCurOut + 1, pCurOut, numFractionDigits);
  1384. pCurOut[0] = (byte)'.';
  1385. pCurOut += (1 + numFractionDigits);
  1386. bufferSize -= (1 + numFractionDigits);
  1387. }
  1388. // add trailing zeros up to precision length
  1389. if (precision > (int)numFractionDigits && bufferSize > 1)
  1390. {
  1391. // add a decimal point if this is the first fractional digit we are printing
  1392. if (numFractionDigits == 0)
  1393. {
  1394. *pCurOut = (byte)'.';
  1395. ++pCurOut;
  1396. --bufferSize;
  1397. }
  1398. // compute the number of trailing zeros needed
  1399. uint numZeros = (uint)(precision - numFractionDigits);
  1400. if (numZeros > bufferSize - 1)
  1401. numZeros = bufferSize - 1;
  1402. for (byte* pEnd = pCurOut + numZeros; pCurOut < pEnd; ++pCurOut)
  1403. *pCurOut = (byte)'0';
  1404. }
  1405. // print the exponent into a local buffer and copy into output buffer
  1406. if (bufferSize > 1)
  1407. {
  1408. var exponentBuffer = stackalloc byte[5];
  1409. exponentBuffer[0] = (byte)'e';
  1410. if (printExponent >= 0)
  1411. {
  1412. exponentBuffer[1] = (byte)'+';
  1413. }
  1414. else
  1415. {
  1416. exponentBuffer[1] = (byte)'-';
  1417. printExponent = -printExponent;
  1418. }
  1419. //RJ_ASSERT(printExponent < 1000);
  1420. uint hundredsPlace = (uint)(printExponent / 100);
  1421. uint tensPlace = (uint)((printExponent - hundredsPlace * 100) / 10);
  1422. uint onesPlace = (uint)((printExponent - hundredsPlace * 100 - tensPlace * 10));
  1423. exponentBuffer[2] = (byte)('0' + hundredsPlace);
  1424. exponentBuffer[3] = (byte)('0' + tensPlace);
  1425. exponentBuffer[4] = (byte)('0' + onesPlace);
  1426. // copy the exponent buffer into the output
  1427. uint maxExponentSize = bufferSize - 1;
  1428. uint exponentSize = (5 < maxExponentSize) ? 5 : maxExponentSize;
  1429. Unsafe.CopyBlock(pCurOut, exponentBuffer, exponentSize);
  1430. pCurOut += exponentSize;
  1431. bufferSize -= exponentSize;
  1432. }
  1433. //RJ_ASSERT(bufferSize > 0);
  1434. //pCurOut[0] = '\0';
  1435. return (int)(pCurOut - pOutBuffer);
  1436. }
  1437. //******************************************************************************
  1438. // Print special case values for infinities and NaNs.
  1439. // The output string is always NUL terminated and the string length (not
  1440. // including the NUL) is returned.
  1441. //******************************************************************************
  1442. private static readonly byte[] InfinityString = new byte[]
  1443. {
  1444. (byte) 'I',
  1445. (byte) 'n',
  1446. (byte) 'f',
  1447. (byte) 'i',
  1448. (byte) 'n',
  1449. (byte) 'i',
  1450. (byte) 't',
  1451. (byte) 'y',
  1452. };
  1453. private static readonly byte[] NanString = new byte[]
  1454. {
  1455. (byte) 'N',
  1456. (byte) 'a',
  1457. (byte) 'N',
  1458. };
  1459. private static unsafe void FormatInfinityNaN(byte* dest, ref int destIndex, int destLength, ulong mantissa, bool isNegative, FormatOptions formatOptions)
  1460. {
  1461. //RJ_ASSERT(bufferSize > 0);
  1462. int length = mantissa == 0 ? 8 + (isNegative ? 1 : 0) : 3;
  1463. int align = formatOptions.AlignAndSize;
  1464. // left align
  1465. if (AlignLeft(dest, ref destIndex, destLength, align, length)) return;
  1466. // Check for infinity
  1467. if (mantissa == 0)
  1468. {
  1469. if (isNegative)
  1470. {
  1471. if (destIndex >= destLength) return;
  1472. dest[destIndex++] = (byte)'-';
  1473. }
  1474. for (int i = 0; i < 8; i++)
  1475. {
  1476. if (destIndex >= destLength) return;
  1477. dest[destIndex++] = InfinityString[i];
  1478. }
  1479. }
  1480. else
  1481. {
  1482. for (int i = 0; i < 3; i++)
  1483. {
  1484. if (destIndex >= destLength) return;
  1485. dest[destIndex++] = NanString[i];
  1486. }
  1487. }
  1488. // right align
  1489. AlignRight(dest, ref destIndex, destLength, align, length);
  1490. }
  1491. // ------------------------------------------------------------------------------
  1492. // Part of the following code is taking some constants and code from
  1493. // https://github.com/dotnet/runtime/blob/75036ffec9473dd1d948c052c041fdedd7784ac9/src/libraries/System.Private.CoreLib/src/System/Number.Formatting.cs
  1494. // Licensed to the .NET Foundation under one or more agreements.
  1495. // The .NET Foundation licenses this file to you under the MIT license.
  1496. // See the https://github.com/dotnet/runtime/blob/master/LICENSE.TXT file for more information.
  1497. // ------------------------------------------------------------------------------
  1498. // SinglePrecision and DoublePrecision represent the maximum number of digits required
  1499. // to guarantee that any given Single or Double can roundtrip. Some numbers may require
  1500. // less, but none will require more.
  1501. private const int SinglePrecision = 9;
  1502. private const int DoublePrecision = 17;
  1503. internal const int SingleNumberBufferLength = SinglePrecision + 1; // + zero
  1504. internal const int DoubleNumberBufferLength = DoublePrecision + 1; // + zero
  1505. // SinglePrecisionCustomFormat and DoublePrecisionCustomFormat are used to ensure that
  1506. // custom format strings return the same string as in previous releases when the format
  1507. // would return x digits or less (where x is the value of the corresponding constant).
  1508. // In order to support more digits, we would need to update ParseFormatSpecifier to pre-parse
  1509. // the format and determine exactly how many digits are being requested and whether they
  1510. // represent "significant digits" or "digits after the decimal point".
  1511. private const int SinglePrecisionCustomFormat = 7;
  1512. private const int DoublePrecisionCustomFormat = 15;
  1513. /// <summary>
  1514. /// Format a float 32-bit to a general format to the specified destination buffer.
  1515. /// </summary>
  1516. /// <param name="dest">Destination buffer.</param>
  1517. /// <param name="destIndex">Current index in destination buffer.</param>
  1518. /// <param name="destLength">Maximum length of destination buffer.</param>
  1519. /// <param name="value">The float 32 value to format.</param>
  1520. /// <param name="formatOptions">Formatting options.</param>
  1521. [MethodImpl(MethodImplOptions.NoInlining)]
  1522. private static unsafe void ConvertFloatToString(byte* dest, ref int destIndex, int destLength, float value, FormatOptions formatOptions)
  1523. {
  1524. // deconstruct the floating point value
  1525. tFloatUnion32 floatUnion = default;
  1526. floatUnion.m_floatingPoint = value;
  1527. uint floatExponent = floatUnion.GetExponent();
  1528. uint floatMantissa = floatUnion.GetMantissa();
  1529. // if this is a special value
  1530. if (floatExponent == 0xFF)
  1531. {
  1532. FormatInfinityNaN(dest, ref destIndex, destLength, floatMantissa, floatUnion.IsNegative(), formatOptions);
  1533. }
  1534. // else this is a number
  1535. else
  1536. {
  1537. // factor the value into its parts
  1538. uint mantissa;
  1539. int exponent;
  1540. uint mantissaHighBitIdx;
  1541. bool hasUnequalMargins;
  1542. if (floatExponent != 0)
  1543. {
  1544. // normalized
  1545. // The floating point equation is:
  1546. // value = (1 + mantissa/2^23) * 2 ^ (exponent-127)
  1547. // We convert the integer equation by factoring a 2^23 out of the exponent
  1548. // value = (1 + mantissa/2^23) * 2^23 * 2 ^ (exponent-127-23)
  1549. // value = (2^23 + mantissa) * 2 ^ (exponent-127-23)
  1550. // Because of the implied 1 in front of the mantissa we have 24 bits of precision.
  1551. // m = (2^23 + mantissa)
  1552. // e = (exponent-127-23)
  1553. mantissa = (uint)((1UL << 23) | floatMantissa);
  1554. exponent = (int)(floatExponent - 127 - 23);
  1555. mantissaHighBitIdx = 23;
  1556. hasUnequalMargins = (floatExponent != 1) && (floatMantissa == 0);
  1557. }
  1558. else
  1559. {
  1560. // denormalized
  1561. // The floating point equation is:
  1562. // value = (mantissa/2^23) * 2 ^ (1-127)
  1563. // We convert the integer equation by factoring a 2^23 out of the exponent
  1564. // value = (mantissa/2^23) * 2^23 * 2 ^ (1-127-23)
  1565. // value = mantissa * 2 ^ (1-127-23)
  1566. // We have up to 23 bits of precision.
  1567. // m = (mantissa)
  1568. // e = (1-127-23)
  1569. mantissa = floatMantissa;
  1570. exponent = 1 - 127 - 23;
  1571. mantissaHighBitIdx = LogBase2(mantissa);
  1572. hasUnequalMargins = false;
  1573. }
  1574. var precision = formatOptions.Specifier == 0 ? -1 : formatOptions.Specifier;
  1575. var bufferSize = Math.Max(SingleNumberBufferLength, precision + 1);
  1576. var pOutBuffer = stackalloc byte[bufferSize];
  1577. if (precision < 0)
  1578. {
  1579. precision = SinglePrecisionCustomFormat;
  1580. }
  1581. int printExponent;
  1582. uint numPrintDigits = Dragon4(mantissa,
  1583. exponent,
  1584. mantissaHighBitIdx,
  1585. hasUnequalMargins,
  1586. CutoffMode.TotalLength,
  1587. (uint)precision,
  1588. pOutBuffer,
  1589. (uint)(bufferSize - 1),
  1590. out printExponent);
  1591. pOutBuffer[numPrintDigits] = 0;
  1592. // Negative 0 are displayed as 0
  1593. bool isNegative = floatUnion.IsNegative();
  1594. if (floatUnion.m_integer == ((uint)1 << 31))
  1595. {
  1596. isNegative = false;
  1597. }
  1598. var number = new NumberBuffer(NumberBufferKind.Float, pOutBuffer, (int)numPrintDigits, printExponent + 1, isNegative);
  1599. FormatNumber(dest, ref destIndex, destLength, ref number, precision, formatOptions);
  1600. }
  1601. }
  1602. /// <summary>
  1603. /// Format a float 64-bit to a general format to the specified destination buffer.
  1604. /// </summary>
  1605. /// <param name="dest">Destination buffer.</param>
  1606. /// <param name="destIndex">Current index in destination buffer.</param>
  1607. /// <param name="destLength">Maximum length of destination buffer.</param>
  1608. /// <param name="value">The float 64 value to format.</param>
  1609. /// <param name="formatOptions">Formatting options.</param>
  1610. [MethodImpl(MethodImplOptions.NoInlining)]
  1611. private static unsafe void ConvertDoubleToString(byte* dest, ref int destIndex, int destLength, double value, FormatOptions formatOptions)
  1612. {
  1613. // deconstruct the floating point value
  1614. tFloatUnion64 floatUnion = default;
  1615. floatUnion.m_floatingPoint = value;
  1616. uint floatExponent = floatUnion.GetExponent();
  1617. ulong floatMantissa = floatUnion.GetMantissa();
  1618. // if this is a special value
  1619. if (floatExponent == 0x7FF)
  1620. {
  1621. FormatInfinityNaN(dest, ref destIndex, destLength, floatMantissa, floatUnion.IsNegative(), formatOptions);
  1622. }
  1623. // else this is a number
  1624. else
  1625. {
  1626. // factor the value into its parts
  1627. ulong mantissa;
  1628. int exponent;
  1629. uint mantissaHighBitIdx;
  1630. bool hasUnequalMargins;
  1631. if (floatExponent != 0)
  1632. {
  1633. // normal
  1634. // The floating point equation is:
  1635. // value = (1 + mantissa/2^52) * 2 ^ (exponent-1023)
  1636. // We convert the integer equation by factoring a 2^52 out of the exponent
  1637. // value = (1 + mantissa/2^52) * 2^52 * 2 ^ (exponent-1023-52)
  1638. // value = (2^52 + mantissa) * 2 ^ (exponent-1023-52)
  1639. // Because of the implied 1 in front of the mantissa we have 53 bits of precision.
  1640. // m = (2^52 + mantissa)
  1641. // e = (exponent-1023+1-53)
  1642. mantissa = (1UL << 52) | floatMantissa;
  1643. exponent = (int)(floatExponent - 1023 - 52);
  1644. mantissaHighBitIdx = 52;
  1645. hasUnequalMargins = (floatExponent != 1) && (floatMantissa == 0);
  1646. }
  1647. else
  1648. {
  1649. // subnormal
  1650. // The floating point equation is:
  1651. // value = (mantissa/2^52) * 2 ^ (1-1023)
  1652. // We convert the integer equation by factoring a 2^52 out of the exponent
  1653. // value = (mantissa/2^52) * 2^52 * 2 ^ (1-1023-52)
  1654. // value = mantissa * 2 ^ (1-1023-52)
  1655. // We have up to 52 bits of precision.
  1656. // m = (mantissa)
  1657. // e = (1-1023-52)
  1658. mantissa = floatMantissa;
  1659. exponent = 1 - 1023 - 52;
  1660. mantissaHighBitIdx = LogBase2((uint)mantissa);
  1661. hasUnequalMargins = false;
  1662. }
  1663. var precision = formatOptions.Specifier == 0 ? -1 : formatOptions.Specifier;
  1664. var bufferSize = Math.Max(DoubleNumberBufferLength, precision + 1);
  1665. var pOutBuffer = stackalloc byte[bufferSize];
  1666. if (precision < 0)
  1667. {
  1668. precision = DoublePrecisionCustomFormat;
  1669. }
  1670. int printExponent;
  1671. uint numPrintDigits = Dragon4(mantissa,
  1672. exponent,
  1673. mantissaHighBitIdx,
  1674. hasUnequalMargins,
  1675. CutoffMode.TotalLength,
  1676. (uint)precision,
  1677. pOutBuffer,
  1678. (uint)(bufferSize - 1),
  1679. out printExponent);
  1680. pOutBuffer[numPrintDigits] = 0;
  1681. // Negative 0 are displayed as 0
  1682. bool isNegative = floatUnion.IsNegative();
  1683. if (floatUnion.m_integer == ((ulong)1 << 63))
  1684. {
  1685. isNegative = false;
  1686. }
  1687. var number = new NumberBuffer(NumberBufferKind.Float, pOutBuffer, (int)numPrintDigits, printExponent + 1, isNegative);
  1688. FormatNumber(dest, ref destIndex, destLength, ref number, precision, formatOptions);
  1689. }
  1690. }
  1691. }
  1692. }