printf函数接受一个参数类型,例如%d或%i为带符号的整型。然而,我没有看到任何长值。
当前回答
这取决于,如果你指的是无符号长,格式化字符是“%lu”。如果您指的是带符号的长字符,则格式化字符为“%ld”。
其他回答
这取决于,如果你指的是无符号长,格式化字符是“%lu”。如果您指的是带符号的长字符,则格式化字符为“%ld”。
在大多数平台上,long和int的大小相同(32位)。不过,它确实有自己的格式说明符:
long n;
unsigned long un;
printf("%ld", n); // signed
printf("%lu", un); // unsigned
对于64位,你需要一个long long:
long long n;
unsigned long long un;
printf("%lld", n); // signed
printf("%llu", un); // unsigned
哦,当然,在Windows中是不同的:
printf("%l64d", n); // signed
printf("%l64u", un); // unsigned
通常,当我打印64位值时,我发现用十六进制打印它们很有帮助(通常使用很大的数字,它们是指针或位字段)。
unsigned long long n;
printf("0x%016llX", n); // "0x" followed by "0-padded", "16 char wide", "long long", "HEX with 0-9A-F"
将打印:
0x00000000DEADBEEF
Btw, "long" doesn't mean that much anymore (on mainstream x64). "int" is the platform default int size, typically 32 bits. "long" is usually the same size. However, they have different portability semantics on older platforms (and modern embedded platforms!). "long long" is a 64-bit number and usually what people meant to use unless they really really knew what they were doing editing a piece of x-platform portable code. Even then, they probably would have used a macro instead to capture the semantic meaning of the type (eg uint64_t).
char c; // 8 bits
short s; // 16 bits
int i; // 32 bits (on modern platforms)
long l; // 32 bits
long long ll; // 64 bits
在过去,“int”是16位。你可能会认为它现在是64位的,但不,那会导致疯狂的可移植性问题。当然,即便如此,这也是对神秘而历史悠久的真相的一种简化。看到维基:整数
我需要打印unsigned long long,所以我找到了这个作品:
unsigned long long n;
printf("%llu", n);
对于所有其他组合,我相信您使用printf手册中的表,为您试图打印的任何类型取行,然后列标签(就像我上面对printf("%llu", n)所做的那样)。
我认为明确地回答这个问题需要知道编译器的名称和版本,以及它正在编译的平台(CPU类型,操作系统等)。
我想你的意思是:
unsigned long n;
printf("%lu", n); // unsigned long
or
long n;
printf("%ld", n); // signed long