brick / math

Arbitrary-precision arithmetic library for PHP
MIT License
1.83k stars 78 forks source link

`gmp_export` equivalent #70

Closed Spomky closed 2 years ago

Spomky commented 2 years ago

Hi,

I am not sure if there is an equivalent method for gmp_export. In my case, I have a GMP object that I need to export using the following parameters:

$bin = gmp_export($value, 1, GMP_MSW_FIRST | GMP_BIG_ENDIAN);

Any idea?

BenMorel commented 2 years ago

Hi, the only binary export option available right now is BigInteger::toBytes(), which outputs the number as Big Endian, which may be what you're looking for?

There is currently no support for little endian, and I have no idea what GMP_MSW_FIRST and GMP_LSW_FIRST do. Does that stand for Most/Least Signifiant Word? How many bytes is a word? When is it useful?

Spomky commented 2 years ago

Hi,

Actually you are right. I just needed to set the second parameter (signed) to false to get it working.

BenMorel commented 2 years ago

Glad this is useful to you! Adding an option to control endianness would be nice, though.

Spomky commented 2 years ago

Yes indeed. I will propose a PR.

I also tried to find other useful GMP functions such as gmp_setbit or gmp_scan1/gmp_scan0. I am not sure if such function exist on BCMath side, but it could be nice to add them as wall.

WDYT?

BenMorel commented 2 years ago

I'm not against a PR for those, what would you use scan0/scan1 for, though?

Spomky commented 2 years ago

I needed those method to convert IEEE 754 mantissa/exponent tuples (https://github.com/Spomky-Labs/pki-framework/commit/9d3a37dd99f29c7a49b51f2fc2ac9fb05f9a8a31#diff-1329957db3e8301016690cb1fdcbe53d50611e9cb9ecd5d8c568eb60616c909f). But the code now looks ugly and non-optimized. Bit manipulation function would help a lot in this case. I don't have any other use case in mind, but searching for bits and modify them if something I commonly do when working on crypto libraries (signature, encryption and key conversions). I will implement the IEEE754 conversion tool here into the CBOR library. At the moment, the library is able to convert the mantissa/exponent into a float/int, but the inversed operation is not yet possible.