C语言 如何在C中显示unsigned long long的最大值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3897727/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:38:36  来源:igfitidea点击:

How to display the maximum value of a unsigned long long in C?

ctypeslong-integer

提问by Lazer

What am I doing wrong here?

我在这里做错了什么?

$ cat size.c
#include<stdio.h>
#include<math.h>

int main() {

printf ("sizeof unsigned int = %d bytes.\n", sizeof(unsigned int));
printf ("sizeof unsigned long long = %d bytes.\n", sizeof(unsigned long long));

printf ("max unsigned int = %d\n", (int)(pow(2, 32) - 1));
printf ("max unsigned long long = %lld\n", (unsigned long long)(pow(2, 64) - 1));

}
$ gcc size.c -o size
$ ./size
sizeof unsigned int = 4 bytes.
sizeof unsigned long long = 8 bytes.
max unsigned int = 2147483647
max unsigned long long = -1
$ 

I am expecting 18446744073709551615as output instead of a -1at the last line.

我期望18446744073709551615作为输出而不是-1最后一行。



Okay, I completely missed that I was getting the wrong value for 232- 1, which should have been 4294967295, not 2147483647. Things make more sense now.

好吧,我完全没有注意到我得到了错误的 2 32- 1值,它应该是 4294967295,而不是 2147483647。现在事情变得更有意义了。

回答by Jens Gustedt

Just don't suppose that it has a certain value use ULLONG_MAX

只是不要假设它有一定的价值用途 ULLONG_MAX

回答by sepp2k

Use %llu, not %lld. dis for signed integers, so printfdisplays it as a signed long long.

使用%llu,不是%lldd用于有符号整数,因此将其printf显示为有符号 long long。

回答by slezica

Edit: changed ~0 to (type) -1 as per Christoph's suggestion. See the comments below.

编辑:根据克里斯托夫的建议,将 ~0 更改为 (type) -1。请参阅下面的评论。

You can get the maximum value of an unsigned type doing the following:

您可以通过执行以下操作获得无符号类型的最大值:

unsigned long long x = (unsigned long long) -1;

Easier, right? =). Second, you are telling printf()to interpret the given variable as a long long decimal, which is signed. Try this instead:

更容易,对吧?=)。其次,您告诉printf()将给定的变量解释为带符号的长长十进制数。试试这个:

unsigned long long x = (unsigned long long) -1;
printf("%llu", x);

%llumeans "long long unsigned".

%llu意思是“long long unsigned”。

回答by Kiril Kirov

unsigned long long ulTestMax = -1;
printf ("max unsigned long long = %llu\n", ulTestMax );

this works in C++, should work here, too.

这适用于 C++,也应该适用于这里。

回答by cyber_raj

Whoever done -1 to Kiril Kirov post pls take a look here:

谁对基里尔·基洛夫 (Kiril Kirov) 发表了 -1 评论,请看这里:

Is it safe to use -1 to set all bits to true?Dingo post

使用 -1 将所有位设置为 true 是否安全?野狗邮政

In Kiril post only slight modification required regarding sign extension:

在 Kiril 帖子中,仅需要对符号扩展进行轻微修改:

unsigned long long ulTestMax = -1LLu; 

-1 is antipattern, it'll do the job if u dont want to go with the solution provided by lmits.h

-1 是反模式,如果你不想使用 lmits.h 提供的解决方案,它会完成这项工作