Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I printf() a uint16_t?

I need to use printf() to print a uint16_t. This SO answer (How to print uint32_t and uint16_t variables value?) says I need to use inttypes.h.

However, I'm working on an embedded system and inttypes.h is not available. How do I print a uint16_t when the format specifier for a uint16_t is not available?

like image 846
user9993 Avatar asked Mar 18 '15 01:03

user9993


People also ask

What is uint16_t in C?

uint16_t is unsigned 16-bit integer. unsigned short int is unsigned short integer, but the size is implementation dependent. The standard only says it's at least 16-bit (i.e, minimum value of UINT_MAX is 65535 ).

What is %U in printf?

In the printf statement when %u is used to print the value of the char c, then the ASCII value of 'a' is printed.

How do I printf a double?

We can print the double value using both %f and %lf format specifier because printf treats both float and double are same. So, we can use both %f and %lf to print a double value.

How do I print a string in printf?

We can print the string using %s format specifier in printf function. It will print the string from the given starting address to the null '\0' character. String name itself the starting address of the string. So, if we give string name it will print the entire string.


1 Answers

You should use the style of inttypes.h but define the symbols yourself. For example:

#define PRIu8 "hu" #define PRId8 "hd" #define PRIx8 "hx" #define PRIu16 "hu" #define PRId16 "hd" #define PRIx16 "hx" #define PRIu32 "u" #define PRId32 "d" #define PRIx32 "x" #define PRIu64 "llu" // or possibly "lu" #define PRId64 "lld" // or possibly "ld" #define PRIx64 "llx" // or possibly "lx" 

Figure them out for your machine and use them. Take a look at others in inttypes.h and figure which you will need.

This way, your code will be more portable. I've been doing embedded systems work since the late 70's. Trust me: portability is important.

like image 58
Jeff Learman Avatar answered Sep 20 '22 18:09

Jeff Learman