计算和使用 uint32_t 的最大值
我知道 UINT32_MAX
存在,但我无法使用它。我尝试了 printf("%d\n", UINT32_MAX);
并打印出了 -1
。使用 %ld
而不是 %d
给我带来了错误,UINT32_MAX
是 unsigned int 类型并且需要 %d 将其打印出来。
请帮忙,我理想地想要的是一个宏/枚举,它保存了 word_t 的最大值,这是我定义的类型,目前是 uint32_t 。
我希望我清楚地表达了我想要的东西,如果没有,请随时询问。
编辑
我忘了说我实际上想做什么。所有这些都将用于将整数数组全部设置为最大值,因为该整数数组实际上是一个位图,它将所有位设置为 1。
I know that UINT32_MAX
exists, but I haven't been able to use it. I tried printf("%d\n", UINT32_MAX);
and it printed out -1
. Using %ld
instead of %d
presented me with the error that UINT32_MAX
is of the type unsigned int and needs %d
to print it out.
Please help, what I ideally want is a macro/enum that holds the maximum value of word_t
which is a type defined by me which currently is uint32_t
.
I hope that I made clear what I want, if not please feel free to ask.
EDIT
I forgot to say what I'm actually trying to do. All of this will be used to set an array of integers all to their maximum value, because that array of integers actually is a bitmap that will set all bits to 1.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
打印
uintN_t
对象的可移植方法是将其转换为uintmax_t
并使用j
长度修饰符和u
code> 转换说明符:j
表示参数是intmax_t
或uintmax_t
;u
表示它是无符号的,因此它是一个uintmax_t
。或者,您可以使用
中定义的格式字符串(在这种情况下,您将使用PRIu32
):您不能只使用
%u
因为不保证int
至少用 32 位表示(它只需要用至少 16 位表示)。The portable way to print a
uintN_t
object is to cast it to auintmax_t
and use thej
length modifier with theu
conversion specifier:The
j
means that the argument is either anintmax_t
or auintmax_t
; theu
means it is unsigned, so it is auintmax_t
.Or, you can use the format strings defined in
<inttypes.h>
(n this case, you'd usePRIu32
):You can't just use
%u
because it isn't guaranteed thatint
is represented by at least 32 bits (it only needs to be represented by at least 16 bits).您遇到了特定问题,因为
%d
是经过签名的格式化程序。有多种方法可以修复它(已经建议了两种),但真正正确的方法是使用
中定义的格式说明符:You encountered your specific problem because
%d
is a signed formatter.There are a number of ways to fix it (two have already been suggested), but the really correct way is to use the format specifiers defined in
<inttypes.h>
:%d
用于有符号整数。使用%u
。编辑:忽略这个答案并使用詹姆斯的答案,它更完整。
%d
is for signed integers. Use%u
.EDIT: Ignore this answer and use James's, which is more complete.
如果要将 unsigned int 数组设置为最大值,可以通过 memset 来完成:
memset(array, 0xFF, sizeof(unsigned int) * arraysize);
If you're setting an array of unsigned int to the max values you could do it via memset:
memset(array, 0xFF, sizeof(unsigned int) * arraysize);