Skip to content

Instantly share code, notes, and snippets.

@sleepdefic1t
Created January 17, 2020 02:31
Show Gist options
  • Save sleepdefic1t/7befce66d95136ed01fb452db25195e9 to your computer and use it in GitHub Desktop.
Save sleepdefic1t/7befce66d95136ed01fb452db25195e9 to your computer and use it in GitHub Desktop.
/*******************************************************************************
*
* Copyright (c) Simon Downey <[email protected]>
*
* The MIT License (MIT)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
******************************************************************************/
#ifndef NUM_TO_STRING_H
#define NUM_TO_STRING_H
#include <stdint.h>
#include <string.h>
const size_t MAX_NUM_TO_STRING_SIZE = 24;
static void NumToString(int64_t value, char* out) {
if (out == NULL) {
out[0] = '\0';
return;
}
if (value == 0) {
out[0] = '0';
out[1] = '\0';
return;
}
size_t numDigits = 0UL;
int64_t base = 1LL;
int64_t tempInt = value;
const size_t maxTmpSize = 24;
if (value < 0) {
out[0] = '-';
tempInt = -tempInt;
}
while (base <= tempInt) {
base *= 0x0A;
numDigits++;
}
if (numDigits > maxTmpSize - 1) {
out[0] = '\0';
return;
}
base /= 0x0A;
for (size_t i = 0; i < numDigits; i++) {
out[i + (size_t)(value < 0)] = '0' + ((tempInt / base) % 0x0A);
base /= 0x0A;
}
out[numDigits + (size_t)(value < 0)] = '\0';
}
static void NumToFloatString(int64_t amount, size_t decimals, char* out) {
char temp[MAX_NUM_TO_STRING_SIZE];
NumToString(amount, temp);
size_t outLen = strlen(temp);
if (decimals > outLen - (amount < 0) - 1 ||
temp[0] == '0') {
out[0] = '\0';
return;
}
if (decimals > 0) {
size_t offset = + outLen - decimals;
strncpy(out, temp, offset);
out[offset] = '.';
strncpy(out + offset + 1,
temp + offset,
outLen - offset + 1);
}
else {
strncpy(out, temp, outLen);
}
}
#endif //#define NUM_TO_STRING_HPP
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment