简体   繁体   中英

c++ and php HEX

i this code in c++ which converts integer to HEX, but the output in php is different

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);
?>

output: 174EC88D4410

how can i get the same HEX value in php as the one in c++?

It is simply a programming error to use atoi , since you cannot know whether the conversion succeeded or not. The correct function to use is strtol (or strtoll ). The corrected program should look like this:

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

For me this says:

Conversion error: Numerical result out of range

You're overflowing the capacity of the integer. Use a long instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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