Priti's Technical Corner

February 20, 2010

GMP Bitwise Operator

Filed under: Uncategorized — Tags: , , — pritisolanki @ 12:47 am

What is GMP?
GNU MP Bignum Library .GMP is a free library for arbitrary precision arithmetic, operating on signed integers, rational numbers, and floating point numbers.

How to install?
On windows

1. Locate php.ini
2. Uncomment ‘extension=php_gmp.dll’
3. Restart your server

How to start working on it !!

Example 1:

$m_string=’1101′;
$c_string=’1100′;

$and_result=gmp_and($m_string,$c_string);

echo “And result: “.gmp_strval($and_result);

Output: And result: 1100

Example 2:
$m_string=’00000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000111111000001111111′;

$c_string=’000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000011111111111111100′;

echo “And result: “.gmp_strval($and_result);

Output: And result: 321675870900800

What went wrong here !!!

The output which is shown to you is of gmp integer type.So, a quick thought is to convert it in to binary and see !!

echo “<br/>Base convert:”.base_convert($and_result,10,2);
Base convert:100

Wrong output !! I searched the google for the same error but everyone says it is the right output !! I tried applying all the arithmetic I could and I knew!!

I spend one full day to understand this behavior and I finally came to the conclusion that it was indeed correct . I realized that what I was thinking was actually wrong but what I was expecting was absolutely right. The correction I made in my code is as follows

$m_string=gmp_init($m_string,2);
$c_string=gmp_init($c_string,2);
$andresult=gmp_and($m_string,$c_string);
echo ‘<br/> and string: ‘.gmp_strval($andresult,2);

and It flawlessly worked for me.

When you are working with PHP the and operation simply truncate the starting zero. Therefore, take care while doing  your calculations. Hence this was a little trick involved in working with gmp numbers.

I would appreciate if you can share your experience with GMP-PHP.

Reference
http://gmplib.org/

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: