numeric_conversion.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. #include "numeric_conversion.h"
  2. #include <string.h>
  3. #include "hardware_seam.h"
  4. #include "program_memory.h"
  5. namespace meCoffee {
  6. namespace {
  7. // binary32 bit patterns for 10^-w and 10^+w with w = 1, 2, 4, 8, 16, 32.
  8. const uint32_t kNegativeDecimalPowerBitPatterns[6] MECOFFEE_PROGRAM_MEMORY = {
  9. 0x3dcccccdUL, 0x3c23d70aUL, 0x38d1b717UL, 0x322bcc77UL, 0x24e69595UL, 0x0a4fb11fUL};
  10. const uint32_t kPositiveDecimalPowerBitPatterns[6] MECOFFEE_PROGRAM_MEMORY = {
  11. 0x41200000UL, 0x42c80000UL, 0x461c4000UL, 0x4cbebc20UL, 0x5a0e1bcaUL, 0x749dc5aeUL};
  12. const uint8_t kDecimalPowerWeights[6] = {1, 2, 4, 8, 16, 32};
  13. constexpr uint32_t kSignificandOverflowThreshold = 429496728UL;
  14. constexpr uint16_t kExponentDigitFreezeThreshold = 3200;
  15. constexpr uint32_t kCanonicalNotANumberBitPattern = 0x7fc00000UL;
  16. constexpr uint32_t kPositiveInfinityBitPattern = 0x7f800000UL;
  17. float reinterpretBitPatternAsFloat(uint32_t bitPattern) {
  18. float reinterpretedValue;
  19. memcpy(&reinterpretedValue, &bitPattern, sizeof reinterpretedValue);
  20. return reinterpretedValue;
  21. }
  22. uint32_t reinterpretFloatAsBitPattern(float numericValue) {
  23. uint32_t bitPattern;
  24. memcpy(&bitPattern, &numericValue, sizeof bitPattern);
  25. return bitPattern;
  26. }
  27. uint32_t readProgramMemoryUnsigned32(const uint32_t* programMemoryAddress) {
  28. const uint8_t* firstByte = reinterpret_cast<const uint8_t*>(programMemoryAddress);
  29. uint32_t assembledValue = 0;
  30. for (uint8_t byteIndex = 0; byteIndex < 4; ++byteIndex) {
  31. assembledValue |= static_cast<uint32_t>(hardware::readProgramMemoryByte(firstByte + byteIndex))
  32. << (8 * byteIndex);
  33. }
  34. return assembledValue;
  35. }
  36. bool isWhitespaceCharacter(char character) {
  37. return character == ' ' || (character >= 0x09 && character <= 0x0d);
  38. }
  39. bool isDecimalDigit(char character) { return character >= '0' && character <= '9'; }
  40. char toLowerCaseLetter(char character) {
  41. return (character >= 'A' && character <= 'Z') ? static_cast<char>(character + ('a' - 'A')) : character;
  42. }
  43. bool startsWithCaseInsensitive(const char* text, const char* lowerCasePrefix) {
  44. while (*lowerCasePrefix != '\0') {
  45. if (toLowerCaseLetter(*text) != *lowerCasePrefix) {
  46. return false;
  47. }
  48. ++text;
  49. ++lowerCasePrefix;
  50. }
  51. return true;
  52. }
  53. } // namespace
  54. float parseDecimalFloatingPoint(const char* text, DecimalParseDiagnostics* diagnostics) {
  55. DecimalParseDiagnostics localDiagnostics = {};
  56. DecimalParseDiagnostics& recorded = diagnostics != nullptr ? *diagnostics : localDiagnostics;
  57. recorded = DecimalParseDiagnostics{};
  58. const char* cursor = text;
  59. while (isWhitespaceCharacter(*cursor)) {
  60. ++cursor;
  61. }
  62. bool isNegative = false;
  63. if (*cursor == '-') {
  64. isNegative = true;
  65. ++cursor;
  66. } else if (*cursor == '+') {
  67. ++cursor;
  68. }
  69. if (startsWithCaseInsensitive(cursor, "nan")) {
  70. recorded.consumedCharacterCount = static_cast<uint16_t>(cursor + 3 - text);
  71. return reinterpretBitPatternAsFloat(kCanonicalNotANumberBitPattern);
  72. }
  73. if (startsWithCaseInsensitive(cursor, "inf")) {
  74. cursor += 3;
  75. if (startsWithCaseInsensitive(cursor, "inity")) {
  76. cursor += 5;
  77. }
  78. recorded.consumedCharacterCount = static_cast<uint16_t>(cursor - text);
  79. return reinterpretBitPatternAsFloat(kPositiveInfinityBitPattern | (isNegative ? 0x80000000UL : 0));
  80. }
  81. uint32_t significand = 0;
  82. uint16_t decimalExponentOffset = 0;
  83. uint16_t discardedDigitCount = 0;
  84. bool hasSignificandDigit = false;
  85. bool hasSeenDecimalPoint = false;
  86. bool isDiscardingDigits = false;
  87. for (;; ++cursor) {
  88. const char character = *cursor;
  89. if (isDecimalDigit(character)) {
  90. hasSignificandDigit = true;
  91. if (isDiscardingDigits) {
  92. ++discardedDigitCount;
  93. if (!hasSeenDecimalPoint) {
  94. ++decimalExponentOffset;
  95. }
  96. } else {
  97. if (hasSeenDecimalPoint) {
  98. --decimalExponentOffset;
  99. }
  100. significand = significand * 10 + static_cast<uint8_t>(character - '0');
  101. if (significand >= kSignificandOverflowThreshold) {
  102. isDiscardingDigits = true;
  103. }
  104. }
  105. } else if (character == '.' && !hasSeenDecimalPoint) {
  106. hasSeenDecimalPoint = true;
  107. } else {
  108. break;
  109. }
  110. }
  111. if (!hasSignificandDigit) {
  112. return 0.0f;
  113. }
  114. if (*cursor == 'e' || *cursor == 'E') {
  115. const char* exponentCursor = cursor + 1;
  116. bool isExponentNegative = false;
  117. if (*exponentCursor == '-') {
  118. isExponentNegative = true;
  119. ++exponentCursor;
  120. } else if (*exponentCursor == '+') {
  121. ++exponentCursor;
  122. }
  123. if (isDecimalDigit(*exponentCursor)) {
  124. uint16_t explicitExponent = 0;
  125. while (isDecimalDigit(*exponentCursor)) {
  126. if (explicitExponent < kExponentDigitFreezeThreshold) {
  127. explicitExponent = static_cast<uint16_t>(explicitExponent * 10 + (*exponentCursor - '0'));
  128. }
  129. ++exponentCursor;
  130. }
  131. decimalExponentOffset = static_cast<uint16_t>(
  132. decimalExponentOffset + (isExponentNegative ? static_cast<uint16_t>(0 - explicitExponent) : explicitExponent));
  133. cursor = exponentCursor;
  134. }
  135. }
  136. recorded.retainedSignificand = significand;
  137. recorded.decimalExponentOffset = static_cast<int16_t>(decimalExponentOffset);
  138. recorded.discardedSignificandDigitCount = discardedDigitCount;
  139. recorded.consumedCharacterCount = static_cast<uint16_t>(cursor - text);
  140. float scaledValue = static_cast<float>(significand);
  141. if (isNegative) {
  142. scaledValue = -scaledValue;
  143. }
  144. if (significand == 0) {
  145. return scaledValue;
  146. }
  147. const int16_t signedExponentOffset = static_cast<int16_t>(decimalExponentOffset);
  148. const bool isScalingDownward = signedExponentOffset < 0;
  149. uint16_t remainingExponentMagnitude = isScalingDownward
  150. ? static_cast<uint16_t>(0 - static_cast<uint16_t>(signedExponentOffset))
  151. : static_cast<uint16_t>(signedExponentOffset);
  152. const uint32_t* powerTable = isScalingDownward ? kNegativeDecimalPowerBitPatterns : kPositiveDecimalPowerBitPatterns;
  153. for (int8_t weightIndex = 5; weightIndex >= 0; --weightIndex) {
  154. const float decimalPower = reinterpretBitPatternAsFloat(readProgramMemoryUnsigned32(&powerTable[weightIndex]));
  155. while (remainingExponentMagnitude >= kDecimalPowerWeights[weightIndex]) {
  156. scaledValue *= decimalPower;
  157. remainingExponentMagnitude = static_cast<uint16_t>(remainingExponentMagnitude - kDecimalPowerWeights[weightIndex]);
  158. }
  159. }
  160. const uint32_t scaledBitPattern = reinterpretFloatAsBitPattern(scaledValue);
  161. const bool isInfinite = (scaledBitPattern & 0x7fffffffUL) == kPositiveInfinityBitPattern;
  162. const bool isZero = (scaledBitPattern & 0x7fffffffUL) == 0;
  163. recorded.isOutOfRangeIndicatorRaised = isInfinite || isZero;
  164. return scaledValue;
  165. }
  166. uint32_t convertFloatToUnsigned32(float numericValue, bool* isConversionStatusFlagged) {
  167. bool isFlagged = false;
  168. uint32_t convertedValue = 0;
  169. const uint32_t bitPattern = reinterpretFloatAsBitPattern(numericValue);
  170. const bool isNegative = (bitPattern & 0x80000000UL) != 0;
  171. const uint8_t biasedExponent = static_cast<uint8_t>((bitPattern >> 23) & 0xff);
  172. if (biasedExponent == 0xff) {
  173. isFlagged = true;
  174. } else if (biasedExponent >= 127) {
  175. const uint8_t unbiasedExponent = static_cast<uint8_t>(biasedExponent - 127);
  176. if (unbiasedExponent >= 32) {
  177. isFlagged = true;
  178. } else {
  179. const uint32_t significandWithHiddenBit = (bitPattern & 0x007fffffUL) | 0x00800000UL;
  180. const uint32_t magnitude = unbiasedExponent >= 23
  181. ? significandWithHiddenBit << (unbiasedExponent - 23)
  182. : significandWithHiddenBit >> (23 - unbiasedExponent);
  183. if (magnitude >= 0x80000000UL) {
  184. isFlagged = true;
  185. }
  186. convertedValue = isNegative ? static_cast<uint32_t>(0 - magnitude) : magnitude;
  187. }
  188. }
  189. if (isConversionStatusFlagged != nullptr) {
  190. *isConversionStatusFlagged = isFlagged;
  191. }
  192. return convertedValue;
  193. }
  194. int32_t convertFloatToSigned32(float numericValue) {
  195. bool isFlagged = false;
  196. const uint32_t convertedValue = convertFloatToUnsigned32(numericValue, &isFlagged);
  197. if (isFlagged) {
  198. return INT32_MIN;
  199. }
  200. return static_cast<int32_t>(convertedValue);
  201. }
  202. namespace {
  203. uint32_t parseIntegerPrefix(const char* text, uint8_t bitWidth) {
  204. const char* cursor = text;
  205. while (isWhitespaceCharacter(*cursor)) {
  206. ++cursor;
  207. }
  208. bool isNegative = false;
  209. if (*cursor == '-') {
  210. isNegative = true;
  211. ++cursor;
  212. } else if (*cursor == '+') {
  213. ++cursor;
  214. }
  215. uint32_t accumulated = 0;
  216. while (isDecimalDigit(*cursor)) {
  217. accumulated = accumulated * 10 + static_cast<uint8_t>(*cursor - '0');
  218. ++cursor;
  219. }
  220. if (isNegative) {
  221. accumulated = 0 - accumulated;
  222. }
  223. return bitWidth == 16 ? (accumulated & 0xffffUL) : accumulated;
  224. }
  225. } // namespace
  226. uint16_t parseIntegerPrefixModulo65536(const char* text) {
  227. return static_cast<uint16_t>(parseIntegerPrefix(text, 16));
  228. }
  229. uint32_t parseIntegerPrefixModulo4294967296(const char* text) { return parseIntegerPrefix(text, 32); }
  230. uint8_t formatUnsignedDecimal(uint32_t numericValue, char* outputBuffer) {
  231. char reversedDigits[10];
  232. uint8_t digitCount = 0;
  233. do {
  234. reversedDigits[digitCount++] = static_cast<char>('0' + numericValue % 10);
  235. numericValue /= 10;
  236. } while (numericValue != 0);
  237. for (uint8_t position = 0; position < digitCount; ++position) {
  238. outputBuffer[position] = reversedDigits[digitCount - 1 - position];
  239. }
  240. return digitCount;
  241. }
  242. uint8_t formatSignedDecimal(int32_t numericValue, char* outputBuffer) {
  243. if (numericValue < 0) {
  244. outputBuffer[0] = '-';
  245. return static_cast<uint8_t>(1 + formatUnsignedDecimal(0 - static_cast<uint32_t>(numericValue), outputBuffer + 1));
  246. }
  247. return formatUnsignedDecimal(static_cast<uint32_t>(numericValue), outputBuffer);
  248. }
  249. } // namespace meCoffee