note 90310 added to language.operators.bitwise

From: Date: Wed, 15 Apr 2009 21:22:44 +0000
Subject: note 90310 added to language.operators.bitwise
Groups: php.notes 
Request: Send a blank email to php-notes+get-153363@lists.php.net to get a copy of this message
For those who are looking for a circular bit shift function in PHP (especially useful for cryptographic functions) that works with negtive values, here is a little function I wrote: (Note: It took me almost a whole day to get this to work with negative $num values (I couldn't figure out why it sometimes worked and other times didn't), because PHP only has an arithmatic and not a logical bitwise right shift like I am used to. I.e. 0x80000001>>16 will ouputs (in binary) "1111 1111 1111 1111 1000 0000 0000 0000" instead of "0000 0000 0000 0000 1000 0000 0000 0000" like you would expect. To fix this you have to apply the mask (by bitwise &) equal to 0x7FFFFFFF right shifted one less than the offset you are shifting by.) <?php function circular_shift($num,$offset) { //Do a nondestructive circular bitwise shift, if offset positive shift left, if negative shift right $num=(int)$num; $mask=0x7fffffff; //Mask to cater for the fact that PHP only does arithmatic right shifts and not logical i.e. PHP doesn't give expected output when right shifting negative values if ($offset>0) { $num=($num<<$offset%32) | (($num>>(32-$offset%32)) & ($mask>>(31-$offset%32))); } elseif ($offset<0){ $offset=abs($offset); $num=(($num>>$offset%32) & ($mask>>(-1+$offset%32))) | ($num<<(32-$offset%32)); } return $num; } ?> ---- Server IP: 69.147.83.197 Probable Submitter: 196.25.255.214 ---- Manual Page -- http://www.php.net/manual/en/language.operators.bitwise.php Edit -- https://master.php.net/note/edit/90310 Del: integrated -- https://master.php.net/note/delete/90310/integrated Del: useless -- https://master.php.net/note/delete/90310/useless Del: bad code -- https://master.php.net/note/delete/90310/bad+code Del: spam -- https://master.php.net/note/delete/90310/spam Del: non-english -- https://master.php.net/note/delete/90310/non-english Del: in docs -- https://master.php.net/note/delete/90310/in+docs Del: other reasons-- https://master.php.net/note/delete/90310 Reject -- https://master.php.net/note/reject/90310 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#153363) next »