开发者

Oracle11g large integer to hex string conversion in php

开发者 https://www.devze.com 2023-02-10 04:47 出处:网络
I have a column in table declared as macaddr NUMBER(15) (macaddress integer representation range - up to 15 digits)

I have a column in table declared as macaddr NUMBER(15) (macaddress integer representation range - up to 15 digits)

The PHP fetch this values as a strings, obviously on 32bit system the dechex will not handle that big ints.

How I can ea开发者_开发问答sily convert that strings into hex macaddr representation (human redable)? And same question in opposite direction?


Do you really need to store these informations in a numeric form? Modern computers have plenty of space available.

Anyway you can use PHP to convert numbers larger than that.
My humble solution is to avoid relying on types provided by PHP and use the BCMath Arbitrary Precision Mathematics.
According to the manual the library comes bundled with PHP since release 4.0.4. If you run PHP in Windows it works straight. Otherwise you have to configure with --enable-bcmath .
Thanks to user contributed notes on the PHP.net website I found these two handy functions:

<?php

        /* hexadecimal to/from decimal functions from user contributed notes at http://it.php.net/manual/en/ref.bc.php */

        function bchexdec($hex) {
            if(strlen($hex) == 1) {
                return hexdec($hex);
            } else {
                $remain = substr($hex, 0, -1);
                $last = substr($hex, -1);
                return bcadd(bcmul(16, bchexdec($remain)), hexdec($last));
            }
        }

        function bcdechex($dec) {
            $last = bcmod($dec, 16);
            $remain = bcdiv(bcsub($dec, $last), 16);

            if($remain == 0) {
                return dechex($last);
            } else {
                return bcdechex($remain).dechex($last);
            }
        }

    echo bcdechex (130646634308);

    echo '<br />';

    echo bchexdec ('001e6b256f44');


    ?>


You could find useful the float type, provided by PHP, which is large enough to hold your values. First convert into a float and then insert or update into your database field. The main problem here is to convert floats to/from hexadecimals.

After some work on my own trying to write a hex2dec function I came up with the resource: the PHP manual.

Take a look at the first comment, by Nstiac. He writes a couple of functions to convert Hex strings to Floating point numbers

EDIT: The functions provided revealed to be broken somehow (see comments below)! Use at your risk!

http://www.php.net/manual/en/language.types.float.php

0

精彩评论

暂无评论...
验证码 换一张
取 消