PHP arbitrary precision with dec/hex conversion

116 Views Asked by At

I need to do arbitrary precision math in PHP.

But the bcmath implementation doesn't seem to have ways to convert between decimal and binary/hex.

I need to take an arbitrary precision number WITH RADIX in either decimal or hex, then output in either decimal or hex.

I need arbitrary precision on both sides of the radix in both bases and in the conversion between bases.

I need to put in on a web host, so I probably don't have access to using system commands.

The only thing I can think of right now is my own PHP implementation of arbitrary precision dechex and hexdec. Arbitrary precision on the right side of the radix could be a bit "extra loopy". Then I could just use bcmath for the actual calculation and flip bases as needed with my own PHP functions.

Is there a better way? am I missing something?

Edit..

So I found a solution. Use 1024 for each 10 binary digits or 3 decimal digits to shift the radix until I have enough precision on the integer side.. then shift it back

I can shift binary radix without division operations, and I can use bcdiv on the decimal side

10.01 decimal

Multiply by 1024 (2^10)

Conversation to binary as int

Right 10 bits become fractional part

Or

1.FFFF hex

Convert to binary

Shift 20 bits (increments of 10, enough to put the precision required on the int side of radix)

Convert hex int to decimal

Divide decimal by 2^20

1

There are 1 best solutions below

2
boroboris On

To work with arbitrary precision numbers you could use Brick\Math. To convert between decimal or hex you could use phpsec.

Both libraries offer a part of functionality you require.