0

When I use hexdec() function, it will return float value for large number.

Ex:

  1. $a = hexdec("10111213");

    => output: int(269554195)

  2. $a = hexdec("1011121314151617");

    => output: float(1.1577264523615E+18)

my php version : 7.3.14

In my local environment, it works fine.

when I use in live server with more than 8 digits, it will return in float value.

what am i missing as it will return value with int for point 2?

due to exponential value, it will effect the further process.

are any changes needed in php.ini file?

Community
  • 1
  • 1
Kamal Sanghavi
  • 175
  • 1
  • 12
  • 2
    You're exceeding the range of an integer so PHP will automatically convert it to a float. – Nick Mar 30 '20 at 11:58
  • 3
    _“in my local environent, it will work fine”_ - then you must have a 64bit operating system locally, but only 32bit on your other system. – CBroe Mar 30 '20 at 12:01
  • 1
    You also might want to consider using [`base_convert`](https://www.php.net/manual/en/function.base-convert.php). It will deal with the input and output as strings instead, and avoid any loss of precision caused by type-conversion to a float. See https://3v4l.org/f30Q3 – iainn Mar 30 '20 at 12:02
  • 1
    You should read [documentation](https://www.php.net/hexdec) more often: it says the function returns a [number](https://www.php.net/manual/en/language.pseudo-types.php#language.types.number) – Mike Doe Mar 30 '20 at 13:28

1 Answers1

3

That's beacuase int in PHP have a limit that depends if you are on a 32 or 64 bits system.
32bits: 2,147,483,647
64bits: 9,223,372,036,854,775,807
In this case you go beyond this limit and PHP convert it to a float.

Witzig Adrien
  • 102
  • 12
  • This depends on whether the underlying OS is a 32bit or 64bit system. On a 64bit system, it will be `9,223,372,036,854,775,807` – CBroe Mar 30 '20 at 12:00
  • Ok, I checked in my local system, it is 64 bits and in live server, it is 32 bits. So, could you please suggest what to do for 32 bit system, to convert this type of large numbers from hex to decimal with int output. – Kamal Sanghavi Mar 30 '20 at 12:08
  • Check the answer of this question : https://stackoverflow.com/questions/211345/working-with-large-numbers-in-php – Witzig Adrien Mar 30 '20 at 12:10
  • 2
    Make your live server 64 bit is how you solve the problem. – Dave Mar 30 '20 at 12:10
  • 1
    Changed server from 32 to 64 bits, and issue is resolved. thanks – Kamal Sanghavi Mar 30 '20 at 12:39