Guest User

Make CSV table of GMP options behavior in PHP

a guest
Jul 20th, 2020
548
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.55 KB | None | 0 0
  1. <?php
  2. $posN = gmp_init(0x0123456789ABCDEF);
  3. $negN = gmp_init(-0x0123456789ABCDEF);
  4.  
  5. /**
  6.  * A function to test the behavior of GMP given various bitfield options
  7.  * @boolean $sign determines whether a positive or negative number is used
  8.  * @boolean $word_size is the size of the word passed to gmp_export
  9.  * @boolean $signifigant_w determine whether w is most significant or least signifigant
  10.  * @boolean $endianness is whether big endian or little endian.
  11.  *
  12.  * @return string the calculated and formatted result of the options
  13.  */
  14. function testGmpBehavior($sign, $word_size, $signifigant_w, $endianness) {
  15.     global $posN, $negN;
  16.     $num = $sign ? $posN : $negN;
  17.     $sig = $signifigant_w ? GMP_MSW_FIRST : GMP_LSW_FIRST;
  18.     $endian = $endianness ? GMP_LITTLE_ENDIAN : GMP_BIG_ENDIAN;
  19.     $hex = bin2hex(gmp_export($num, $word_size, $sig | $endian));
  20.     $chunked = strtoupper( chunk_split($hex, 2*$word_size, "_") );
  21.     return substr($chunked, -1) === "_" ? substr($chunked, 0, -1) : $chunked;
  22. }
  23. echo "Sign,Word Size,Sig,Endian,gmp_export Hex Result", PHP_EOL;
  24. for ($sign=1; 0 <= $sign; $sign--)
  25.     for ($wSize=1; $wSize <= 8; $wSize++)
  26.         for ($sigW=1; 0 <= $sigW; $sigW--)
  27.             for ($end=1; 0 <= $end; $end--) {
  28.                 echo !!$sign ? "+pos" : "-neg", ",";
  29.                 echo $wSize, " bytes", ",";
  30.                 echo !!$sigW ? "MSW" : "LSW", ",";
  31.                 echo !!$end ? "little" : "big", ",";
  32.                 echo testGmpBehavior(!!$sign, $wSize, !!$sigW, !!$end);
  33.                 echo PHP_EOL;
  34.             }
Add Comment
Please, Sign In to add comment