printf 64位类型说明符问题 [英] printf 64bit type specifier issue

查看:29
本文介绍了printf 64位类型说明符问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 msdev 2010 中看到 __int64 类型的一些奇怪行为.有人能告诉我发生了什么吗?我想这里有两个问题,首先是如何显示 64 位整数,其次是行为 - 即为什么看起来 __int64 实际上是 32 位整数...

I'm seeing some strange behaviour with __int64 types with msdev 2010. Could anyone enlighten me as to what is going on ? I guess there are 2 issues here, firstly how to display 64bit ints, secondly the behaviour - i.e. why is it looking like __int64 is actually a 32bit int...

#include <stdio.h>

int main()
{
  int vl_idx;
  unsigned __int64 vl_64;
  unsigned __int64 vl_64_test;

  for (vl_idx = 0; vl_idx < 64; vl_idx++)
  {
    vl_64 = 1 << vl_idx;
    printf ("vl_64 (%d) = %I64u\n", vl_idx, vl_64);
    printf ("vl_64 (%d) = %llu\n", vl_idx, vl_64);
    printf ("vl_64 (%d) = %lu\n", vl_idx, vl_64);
  }
  vl_64_test = 1 << 31;
  if (vl_64 > vl_64_test)
     printf ("greater\n");
  if (vl_64 == vl_64_test)
     printf ("equal\n");
  if (vl_64 < vl_64_test)
     printf ("less\n");

  return 0;
}

前 30 次迭代的输出符合预期:

The output is as expected for the first 30 iterations:

vl_64 (0) = 1
vl_64 (0) = 1
vl_64 (0) = 1
vl_64 (1) = 2
vl_64 (1) = 2
vl_64 (1) = 2
...
vl_64 (30) = 1073741824
vl_64 (30) = 1073741824
vl_64 (30) = 1073741824
vl_64 (31) = 18446744071562067968
vl_64 (31) = 18446744071562067968
vl_64 (31) = 2147483648
vl_64 (32) = 1
vl_64 (32) = 1
vl_64 (32) = 1
vl_64 (33) = 2
vl_64 (33) = 2
vl_64 (33) = 2
...
vl_64 (62) = 1073741824
vl_64 (62) = 1073741824
vl_64 (62) = 1073741824
vl_64 (63) = 18446744071562067968
vl_64 (63) = 18446744071562067968
vl_64 (63) = 2147483648
equal

但后来事情?溢出?在第 32 次迭代.这可能只是显示问题,但最后的比较表明并非如此.这是使用 msdev 2010 cl(64 位版本)编译并在 64 位 Windows 操作系统(具有 64 位 CPU)上运行.关于为什么比较指出 1<<31 == 1<<63 的任何建议?

But then things ?overflow? at the 32nd iteration. It's possible this is just a display issue, but the comparison at the end suggests otherwise. This was being compiled with the msdev 2010 cl (64 bit version) and running on a 64bit windows OS (with a 64 bit CPU). Any suggestions as to why the comparison states that 1<<31 == 1<<63 ?

感谢您的建议,

吉姆

推荐答案

在处理比 int 更宽的任何内容时,您需要小心整数文字,例如你需要改变:

You need to be careful with integer literals when dealing with anything wider than int, e.g. you need to change:

vl_64 = 1 << vl_idx;

到:

vl_64 = 1LLU << vl_idx;

否则,在被隐式转换为无符号 64 位结果之前,首先将右侧评估为 int 表达式.

otherwise the right hand side is evaluated as an int expression first before being implicitly cast to an unsigned 64 bit result.

这篇关于printf 64位类型说明符问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆