# Thread: Unsigned right bitwise shift

1. ## Unsigned right bitwise shift

Is it possible to perform an unsigned right bitwise shift in PHP (eg. ">>>" in other languages)?

Example:
PHP Code:
``` //Signed shift: echo (-1 >> 2); //Produces -1 //Pseudo unsigned shift: echo (-1 >>> 2); //Would produce 1073741823  ```
If there is no built-in operator, is there a formula that can be used to emulate this?

2. ## Oops

Don't you hate it when you try to solve a problem for hours, finally break down and ask for help, just to find the solution a few minutes after you post anyway?

Anyway, here's a function that I found hiding in the depths of Google:
PHP Code:
```     function uRShift(\$a, \$b)     {         \$z = hexdec(80000000);         if (\$z & \$a)         {             \$a = (\$a >> 1);             \$a &= (~\$z);             \$a |= 0x40000000;             \$a = (\$a >> (\$b - 1));         } else {             \$a = (\$a >> \$b);         }         return \$a;     }  ```
Sample:
PHP Code:
``` echo((-1 >> 2) . "<br>\n"); echo(uRShift(-1, 2) . "<br>\n"); /* Output: -1 1073741823 */  ```
Source code taken from: http://www.vision.to/CMS/Home/index.php?pid=288

PHP Code:
``` function logical_rshift(\$value, \$by){  return bindec("0".substr(decbin(\$value),\$by));}echo logical_rshift(-1,2);  ```
I guess the main drawback is that speed can be an issue if it's used often enough.

4. Even better

Off Topic:

All of this is being used as I attempt to find a large prime number with PHP. I'm slowly trying to translate the Java BigInteger functions into PHP in order to accomplish this, but it's slow work.

Do you know of any prime number generators which are written in pure PHP? I'm trying to generate a prime of at least 64 bits in length, but would like it to support possibly even 256 bits...

5. Off Topic:

6. The pure arithmetic (and therefore fastest possible) version of right shift:
PHP Code:
``` function urshift(\$n, \$s) {    return (\$n >= 0) ? (\$n >> \$s) :        ((\$n & 0x7fffffff) >> \$s) |             (0x40000000 >> (\$s - 1));}  ```
Do you know of any prime number generators which are written in pure PHP? I'm trying to generate a prime of at least 64 bits in length, but would like it to support possibly even 256 bits...
In 'pure php' this is hardly possible, there are gmp_prob_prime and gmp_nextprime, although gmp extension is rather exotic.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•