Search code examples
phpmysqlcastingunsignedsigned

How to cast a 32-bit integer from unsigned to signed in MySQL or PHP?


I have a string in PHP (came from some data source), which represents a formatted unsigned 32-bit integer. I need to store it into a MySQL database as a signed 32-bit integer, so that later I can retrieve it from PHP and use it as a (possibly negative) signed integer constant (since PHP doesn't have unsigned integers).

So, what I need is a conversion method, either for PHP or MySQL. It shouldn't be platform-dependent (no endian / 32/64-bit issues).

I know how to convert a signed integer into unsigned using MySQL:

select CAST((-1062726980 & 0xFFFFFFFF) AS UNSIGNED INTEGER);
+------------------------------------------------------+
| CAST((-1062726980 & 0xFFFFFFFF) AS UNSIGNED INTEGER) |
+------------------------------------------------------+
|                                           3232240316 | 
+------------------------------------------------------+

But I can't get it work the other way around (note: MySQL uses 64-bit arithmetic when doing casts).

Thanks.


Solution

  • This:

    $val = (bccomp("2147483647", $val) < 0) ? bcsub($val, "4294967296") : $val;
    

    seems to work, even though it's somewhat slow.