繁体   English   中英

C ++和PHP十六进制

[英]c++ and php HEX

我这个代码在C ++中将整数转换为十六进制,但是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 ++中相同的十六进制值?

使用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

您正在溢出整数的容量。 使用长代替。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM