printf 64bit type specifier issue

空扰寡人 提交于 2019-12-14 01:24:25

问题


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;
}

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

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 ?

Thanks for any suggestions,

Jim


回答1:


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;

to:

vl_64 = 1LLU << vl_idx;

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



来源:https://stackoverflow.com/questions/16415691/printf-64bit-type-specifier-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!