snprintf()

snprintf()

Description

Convert values to text.

Syntax

snprintf(dest[], size, format,...);

Parameters

Variable

Input

Variable

Input

dest[]

The string that will contain the formatted result.

size

The maximum number of cells that the dest parameter can hold. This value includes the zero terminator.

format

The string to store in dest, which may contain placeholders (see the notes below).

...

The parameters for the placeholders. These values may be untagged, weakly tagged, or tagged as rational values.

The format parameter is a string that may contain embedded placeholder codes:

  • %i store a number at this position in decimal radix

  • %f store a floating point number at this position (for implementations that support floating point)

  • %x store a number at this position in hexadecimal radix

  • %X store a number at this position in hexadecimal radix

  • The values for the placeholders follow as parameters in the call

Returns

This function always returns 0.

Function call example

Example of converting values to text
new data1[10]; new data2[5]; main(){ data2[0] = 215; data2[3] = 145; snprintf(data1, sizeof data1, "%x %x", data2[0], data2[3]); // print selected data into text array starting from third element while(1){ Delay(1000); } }

Notes and Warnings

  • You may optionally put a number between the “%” and the letter of the placeholder code. This number indicates the field width; if the size of the parameter to print at the position of the placeholder is smaller than the field width, the field is expanded with spaces.

  • In case offset is needed, keep in mind that while using offset - you still cannot overflow buffer. Meaning that if we start to write from array element no.3  while array size is 10 elements we should not set size variable higher than 8. Otherwise critical error might happen. Here's an example on how it should be done if offset is needed:

Example of converting value to string with offset
new data1[10]; new data2[5]; new offset = 2; main(){ data2[0] = 215; data2[3] = 145; snprintf(data1[offset], (sizeof data1)-offset, "%x %x", data2[0], data2[3]); // print selected data into text array starting from third element while(1){ Delay(1000); } }

Used in Examples

Accelerometer example

BIT64 example

Call by reference example

Ibutton ID example

Struct example

Time example

EEPROM example