Skip to content

Instantly share code, notes, and snippets.

@madex
Created October 20, 2014 10:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save madex/745486eedc14df030e2d to your computer and use it in GitHub Desktop.
Save madex/745486eedc14df030e2d to your computer and use it in GitHub Desktop.
unsigned 32bit output with lenghtInChars width, either filled with '0' or with ' ' depending on fillWith0. if value is bigger than the value that is possible within lenghtInChars, the maximum possible value is shown.
char *itoaUint32VarLen(uint32_t value, uint8_t fillWith0, uint8_t lenghtInChars) {
static uint8_t sBuf0[12]; // maximum Value -2147483649 = 12
uint8_t *sBuf = &sBuf0[11], *sBufWerteBegrenzung;
uint32_t valueAlt; // Alte Wert für schneller % 10 Berechnung
*sBuf = 0;
if (value == 0) {
*--sBuf = '0';
lenghtInChars--;
} else while (value) {
if (!lenghtInChars) {
sBufWerteBegrenzung = sBuf;
while (sBufWerteBegrenzung < &sBuf0[11])
*sBufWerteBegrenzung++ = '9';
break;
}
valueAlt = value;
value /= 10;
*--sBuf = '0' + valueAlt - (value * 10); // schneller als *--sBuf = '0' + (valueAlt % 10)
lenghtInChars--;
}
while (sBuf > sBuf0 && lenghtInChars--) // mit Nullen auffüllen
*--sBuf = fillWith0 ? '0' : ' ';
return *sBuf;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment