Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format specifiers for uint8_t, uint16_t, ...?

Tags:

c++

c++11

scanf

If I have an integer variable I can use sscanf as shown below by using the format specifier %d.

sscanf (line, "Value of integer: %d\n", &my_integer); 

Where can I find format specifiers for uint8_t, uint16_t, uint32_t and uint64_t?

uint64_t has probably %lu.

like image 955
Usman Avatar asked Aug 09 '11 08:08

Usman


People also ask

What is the format specifier for uint8_t?

As far as I understand printf() , it has to know the length of the supplied parameters to be able to parse the variable argument list. Since uint8_t and uint16_t use the same format specifier %u , how does printf() "know" how many bytes to process?

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 uint8_t * in C?

In C, the unsigned 8-bit integer type is called uint8_t . It is defined in the header stdint. h . Its width is guaranteed to be exactly 8 bits; thus, its size is 1 byte.

What is the format specifier for unsigned char?

printf("%u",x);


2 Answers

They are declared in <inttypes.h> as macros: SCNd8, SCNd16, SCNd32 and SCNd64. Example (for int32_t):

sscanf (line, "Value of integer: %" SCNd32 "\n", &my_integer); 

Their format is PRI (for printf)/SCN (for scan) then o, u, x, X d, i for the corresponding specifier then nothing, LEAST, FAST, MAX then the size (obviously there is no size for MAX). Some other examples: PRIo8, PRIuMAX, SCNoFAST16.

Edit: BTW a related question asked why that method was used. You may find the answers interesting.

like image 190
AProgrammer Avatar answered Oct 14 '22 11:10

AProgrammer


As others said, include <stdint.h> header that defines the format macros. In C++, however, define __STDC_FORMAT_MACROS prior to including it. From stdint.h:

/* The ISO C99 standard specifies that these macros must only be    defined if explicitly requested.  */ #if !defined __cplusplus || defined __STDC_FORMAT_MACROS 
like image 20
Maxim Egorushkin Avatar answered Oct 14 '22 12:10

Maxim Egorushkin