fbpx

NUM2STR

NUM2STR TinyAVRLib Tinusaur

NUM2STR is a small library, part of the TinyAVRLib library, for converting numbers to text in three main formats: decimal, hexadecimal, and binary. I have been using it for several years in another library to print debugging information. The library is designed for ATtiny85 microcontrollers or similar, and the goal is to work with a minimum amount of memory for code and data.

Library size (approximately):

Program:    1074 bytes (13.1% Full)  (.text + .data + .bootloader)
Data:           12 bytes (2.3% Full)        (.data + .bss + .noinit)

The library code can be found at: https://gitlab.com/tinusaur/tinyavrlib/

The main files are:

  • tinyavrlib/num2str.h
  • tinyavrlib/num2str.c

The main functions are:

  • uint8_t usint2decascii(uint16_t, char *);
  • uint8_t usint2hexascii(uint16_t, char *);
  • uint8_t usint2binascii(uint16_t, char *);

How to use it

Two arguments must be given to the function: (1) the number to be converted; (2) a pointer to a buffer in which to write the result.

These functions are used in another library: OWOWOD – One-Wire / One-Way Output for Debugging, which is printing debugging information. There are few examples below.

Tinusaur Library Integer to ASCII DEC HEX BIN RealTerm

Convert an integer to decimal with a sign:

char buffer[USINT2DECASCII_MAX_DIGITS + 2]; // One more byte for the sign.
buffer[0] = ' ';   // Init the string.
buffer[USINT2DECASCII_MAX_DIGITS + 1] = '\0';   // Terminate the string.
uint8_t digits = usint2decascii((num < 0 ? -num : num), buffer + 1);
if (num < 0) buffer[digits] = '-';
owowod_print_string(buffer + digits + (num < 0 ? 0 : 1));

Sample result:

A=123
B=-19858
C=-901

Convert an integer to hexadecimal without a sign, filled with leading zeros:

char buffer[USINT2HEXASCII_MAX_DIGITS + 1];
buffer[USINT2HEXASCII_MAX_DIGITS] = '\0';   // Terminate the string.
usint2hexascii(num, buffer);
owowod_print_string(buffer + USINT2HEXASCII_MAX_DIGITS / 2);

Sample result:

D=04D2
E=1DD5
F=CFC7

Convert an integer to a binary without a sign, filled with leading zeros:

char buffer[USINT2BINASCII_MAX_DIGITS + 1];
buffer[USINT2BINASCII_MAX_DIGITS] = '\0';   // Terminate the string.
usint2binascii(num, buffer);
owowod_print_string(buffer);

Sample result:

K=0000000000000001
L=0000000011101010
M=1101110111010101

Other related information

Pages and blog posts about the NUM2STR library.

Information about the OWOWOD library: https://gitlab.com/tinusaur/owowod

The source code is available as open source software at GitLab at https://gitlab.com/tinusaur/tinyavrlib – our primary repository, but there is also a copy at GitHub at https://github.com/tinusaur/tinyavrlib.

Item added to cart.
0 items - $0.00