0

我在 c++ 中的这段代码将整数转换为 HEX,但 php 中的输出不同

C++:

#include <iostream>
#include <stdlib.h>
#include <string>
#include <stdio.h>

using namespace std;

int main(){

  string str1("100106014020");
  int i;

  i = atoi(str1.c_str());
  printf ("HEX value is %X", i);

  return 0;
}

output:
HEX value is 4EC88D44

PHP:

<?php
$num = '100106014020';
$nnum = (int)$num;
echo printf ("%X",$nnum);
?>

输出:174EC88D4410

如何在 php 中获得与在 c++ 中相同的 HEX 值?

4

2 回答 2

3

使用它只是一个编程错误atoi,因为您无法知道转换是否成功。要使用的正确函数是strtol(或strtoll)。更正后的程序应如下所示:

#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <cerrno>

int main()
{
    const char * const str1 = "100106014020";
    char * e;
    long i = std::strtol(str1, &e, 0);

    if (e != 0)
    {
        std::printf("Conversion error: %s\n", strerror(errno));
    }
    else
    {
        std::printf("Conversion succeeded, value = 0x%lX\n", i);
    }
}

对我来说,这说:

Conversion error: Numerical result out of range
于 2012-11-15T15:16:55.853 回答
0

你溢出了整数的容量。改用 long 。

于 2012-11-15T15:13:31.007 回答