【问题标题】:Decimal to hex for int64 in cc中int64的十进制到十六进制
【发布时间】:2011-08-30 08:12:09
【问题描述】:

为什么这段代码不起作用?

#include <iostream>
#include <cstdio>
int main() {
  printf("%X", 1327644190303473294);
}

我收到了 o/p 5f264e8e

但预期的 o/p 是 126cbd5b5f264e8e,由下面的 php 脚本给出

<?php
  echo dechex(1327644190303473294);
?>

【问题讨论】:

  • 问题是:你为什么在 C++ 程序中使用printf? :)
  • 我已经写了这个作为例子。我在 c char 数组缓冲区上进行了 sprint。

标签: c


【解决方案1】:

格式“%X”需要类型“unsigned int”,但参数 2 的类型为“long int”

#include <stdio.h>

int main(void) {
    printf("%lX",1327644190303473294);
    return 0;
}

输出

126CBD5B5F264E8E

【讨论】:

  • long 可能不是 64 位(不在 Windows 上)。
【解决方案2】:

做到这一点的便携方式是

#include <inttypes.h>

然后做:

#include <stdio.h> 
#include <inttypes.h>  // for PRIX64 macro (and INT64_C macro from stdint.h)

int main(void) 
{
    printf("The value is %"PRIX64"\n", INT64_C(1327644190303473294));
    return 0;
}

【讨论】:

  • 是的。我同意 INT64_C() 更好。
  • INT64_C() 不是 C99 标准宏。例如,它不在我的inttypes.h 中(Mac OS X 10.7)。但是,(int64_t)1327644190303473294 也可以正常工作,并且是 C99 标准。
  • 抱歉,我在寻找 INTn_C() 宏的错误标题
  • @JeremyP:是的,它在 stdint.h 中,它必须包含在 inttypes.h 中。我也使用 Mac OS X 10.7,FWIW。
【解决方案3】:

%X 用于int,通常为 32 位。 64 位数字所需的咒语取决于平台。在 Mac 上,它是 %qX

【讨论】:

  • q 在 OS X 10.7 Lion 上已弃用,printf(3)
  • @Mats 任何独立于平台的解决方案?
  • @Vivek:Rudy 的回答与平台无关。
【解决方案4】:

您需要使用不同的格式说明符来指示您的整数是 64 位宽。就目前而言,您的代码将输入解释为 32 位整数。

在 MSVC 中这将是 %I64x,在某些平台上会是 %lx,并且确实有其他说明符。

总之,您需要选择适合您的特定工具集的说明符。

【讨论】:

  • long 可能不是 64 位(不在 Windows 上)。
【解决方案5】:

对于 uint64_t,你可以尝试如下:

uint64_t val = 1327644190303473294;
printf("val: 0x%llx\n", val);

【讨论】:

  • warning: format ‘%llx’ expects argument of type ‘long long unsigned int’, but argument 2 has type ‘uint64_t’
猜你喜欢
  • 2011-12-09
  • 2011-06-01
  • 2018-07-26
  • 2014-04-18
  • 2014-11-30
  • 2011-02-04
  • 2015-11-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多