Skip to content

Instantly share code, notes, and snippets.

@raybellis
Last active November 12, 2020 12:33
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 raybellis/75f67c459aa2bae32be4427f9bad2526 to your computer and use it in GitHub Desktop.
Save raybellis/75f67c459aa2bae32be4427f9bad2526 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
extern void lcddata(unsigned char n);
static inline uint16_t
display_uint16_t_digit(
uint16_t n, uint16_t div,
bool *leading_zero)
{
char digit = 0;
int shift = (div >= 10000) ? 2 : 3; // prevent overflow
char add = 1 << shift;
div <<= shift;
while (add) {
if (n >= div) {
n -= div;
digit += add;
}
div >>= 1;
add >>= 1;
}
if (digit || *leading_zero) {
lcddata(digit + '0');
*leading_zero = true;
}
return n;
}
void display_uint16_t(uint16_t n)
{
bool zero = false;
n = display_uint16_t_digit(n, 10000, &zero);
n = display_uint16_t_digit(n, 1000, &zero);
n = display_uint16_t_digit(n, 100, &zero);
n = display_uint16_t_digit(n, 10, &zero);
lcddata(n + '0');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment