C Programming with Arduino %s and %c are used to print a string and character respectively. You have already seen %d for printing integer decimal numbers, %i does the same thing and %u works with unsigned integers. %x and %X are for printing hexadecimal numbers. %o prints out a number in octal format. Octal is another number system like binary or hexadecimal, but uses base 8. %f is familiar to you and is used to print a floating point number. %e and %E print a number in exponential notation, which is a notation used by scientists and engineers. Table 10-1 C Format Specifiers Format Specifier
Data Type
Print Format
%d or %i
int
Decimal number
%u
unsigned int
Unsigned decimal number
%x
unsigned int
Lowercase hexadecimal
%X
unsigned int
Uppercase hexadecimal
%o
unsigned int
Octal unsigned integer
%c
char or int
Character
%s
string
A string of characters
%f
float
Floating point number
%e
float
Lowercase exponential notation
%E
float
Uppercase exponential notation
10.2 • Field Width Specifiers Revisited We have already seen field width specifiers used with floating point numbers to set the number of digits to print after the decimal point. The number of digits can also be set before the decimal point, or in the case of decimal and hexadecimal numbers, set the number of place holders to the left of the number. As an embedded programmer, you may wish to use this to show the width of a number when using hexadecimal numbers, or to align numbers. For example, the number 0x5 is a 3 bit number (1012), but in a microcontroller or computer, memory is always displayed in multiples of bytes, so we may wish to display this number with padding zeros to represent all 8 bits – 0x05 (0000 01012). The next program, padding, shows how to pad different numbers with zeros or spaces. Create the project using the template file. Project name: padding Project location: CH10\padding main.c #include <stdio.h> #include "stdio_setup.h" int main(void) { UartInit(); // a 3 bit hex number padded to 8 bits printf("0x%X\n", 0x5); // unpadded printf("0x%2X\n", 0x5); // pad with spaces printf("0x%02X\n\n", 0x5); // pad with 0 // a 3 bit hex number padded to 16 bits printf("0x%4X\n", 0x5); // pad with spaces printf("0x%04X\n\n", 0x5); // pad with 0
● 174