I trying to print U32 variable in C, not sure what is the write way
printf("print_variable %u\n", u32");
it gives error, should i force (int)u32 ?
There is no standard type U32
.
Assuming it's an integer type, probably a typedef for a 32-bit unsigned type, you can safely print the value like this:
printf("%lu\n", (unsigned long)u32);
I used unsigned long
rather than unsigned int
because unsigned int
can legally be only 16 bits wide. unsigned long
is guaranteed to be at least 32 bits wide, so it can hold any possible value of type u32
(assuming u32
is defined sanely). For a 64-bit unsigned type, you can safely use unsigned long long
and "%llu"
.
Starting with C99, the standard C library includes a header <stdint.h>
which defines fixed-width types, including uint32_t
, which is probably the same thing as your U32
. I don't suggest making massive modifications to working code just to use the standardized typedefs, but in new code you should probably use uint32_t
. The standard header <inttypes.h>
defines macros for use with printf
, letting you write, as iharob's answer suggests :
uint32_t u32;
printf("%" PRIu32 "\n", u32);
( PRIu32
expands to a string literal; the three string literals "%"
, PRIu32
, and "\\n"
are concatenated by the compiler.)
Personally, though, I find the macro names (which are documented in N1570 section 7.8) difficult to remember. I often just convert to some predefined type that I know is wide enough, as I've shown above.
我假设你的意思是uint32_t
,所以包括inttypes.h并使用
printf("Value: %" PRIu32 "\n", u32);
When uncertain what format specifier to use to print some integer:
If the type is a specified type in C like int, unsigned long long, size_t, uint8_t
, etc., best to used the matching specifier "%d", "%llu", "%zu", "%" PRIu8
, etc. Many resources list the corresponding type to specifier.
#include <inttypes.h> printf("%" PRIu32 "\\n", u32); // type known to be 32-bit unsigned - no padding.
When the type's relationship to standard types is not clear, yet its sign-ness is known, code can cast to a corresponding wide type.
#include <stdint.h> printf("%ju\\n", (uintmax_t) u32); // type is known to be some unsigned integer
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.