Search code examples
phprandomgnugmpbit

PHP: Get the "number of bits per limb" in GNU MP


I want to use the function gmp_random() by GNU MP in PHP. I need to set the exact value of bits I want (for example a random number with 64bit length).

The limiter parameter is multiplied with the "number of bits per limb". How can I get this value? Is that ever equivalent to the bit-count of the CPU or is there any PHP function to get the value?

In the original library it is represent by the const mp_bits_per_limb.


Solution

  • Seems like there's no simple way to solve that.

    You can either pretend that mp_bits_per_limb equals PHP_INT_SIZE*8 and just use that (will work on most, but not all architectures). The resulting bugs will be tough and a worthy thing to debug for any developer. So this is probably the way to go :)

    Or work around it by knowing that mp_bits_per_limb will not be smaller than 16, so you just use "number_of_bits_you_want/16", get a result that has too many bits and gmp_and() your result with 0xFFFF, 0xFFFFFFFF or 0xFFFFFFFFFFFFFFFF to cut it down to 16, 32 or 64 bits.