php or_PHP 位运算符

用户评论:

vivekanand dot pathak25 at gmail dot com (2013-03-16 07:59:30)

$a = 9;

$b = 10;

echo $a & $b;

place value 128 64 32 16 8 4 2 1

$a 0 0 0 0 1 0 0 1 =9

$b 0 0 0 0 1 0 1 0 =10

result 8

only bit they share together is the 8 bit. So 8 gets returned.

$a = 36;

$b = 103;

echo $a & $b;

place value 128 64 32 16 8 4 2 1

$a 0 0 1 0 0 1 0 0 =36

$b 0 1 1 0 0 1 1 1 =103

result 32+4 = 36

the only bits these two share together are the bits 32 and 4 which when added together return 36.

$a = 9;

$b = 10;

echo $a | $b;

place value 128 64 32 16 8 4 2 1

$a 0 0 0 0 1 0 0 1 =9

$b 0 0 0 0 1 0 1 0 =10

result 8+2+1 = 11

3 bits set, in the 8, 2, and 1 column.add those up 8+2+1 and you get 11

$a = 9;

$b = 10;

echo $a ^ $b;

place value 128 64 32 16 8 4 2 1

$a 0 0 0 0 1 0 0 1 =9

$b 0 0 0 0 1 0 1 0 =10

result 2+1 = 3

the 2 bit and the 1 bit that they each have set but don't share. Soooo 2+1 = 3

erich at seachawaii dot com (2012-12-14 03:15:53)

Just a note regarding negative shift values, as the documentation states each shift is an integer multiply or divide (left or right respectively) by 2. That means a negative shift value (the right hand operand) effects the sign of the shift and NOT the direction of the shift as I would have expected.

FE. 0xff >> -2 results in 0x0

and 0xff << -2 result in 0xFFFFFFFFC0000000 (dependant on PHP_INT_MAX)

frankemeks77 at yahoo dot com (2012-08-21 13:24:50)

Just learning Bitwise Shift Operators.

The easiest way to resolve a bitwise  shift operators is my multiply or dividing each step by two for left shift or right shift respectively

Example:

LEFT SHIFT

//same as

RIGHT SHIFT

<?phpecho8>>3;//1?>

//same as

//Solving on a paper 8/2 = 4/2 = 2/2 = 1

wbcarts at juno dot com (2012-05-17 03:52:20)

BITWISE FLAGS for Custom PHP Objects

Sometimes I need a custom PHP Object that holds several boolean TRUE or FALSE values. I could easily include a variable for each of them, but as always, code has a way to get unweildy pretty fast. A more intelligent approach always seems to be the answer, even if it seems to be overkill at first.

I start with an abstract base class which will hold a single integer variable called $flags. This simple integer can hold 32 TRUE or FALSE boolean values. Another thing to consider is to just set certain BIT values without disturbing any of the other BITS -- so included in the class definition is the setFlag($flag, $value) function, which will set only the chosen bit. Here's the abstract base class definition:

protected$flags;/*

* Note: these functions are protected to prevent outside code

* from falsely setting BITS. See how the extending class 'User'

* handles this.

*

*/protected functionisFlagSet($flag)

{

return (($this->flags&$flag) ==$flag);

}

protected functionsetFlag($flag,$value)

{

if($value)

{$this->flags|=$flag;

}

else

{$this->flags&= ~$flag;

}

}

}?>

The class above is abstract and cannot be instantiated, so an extension is required. Below is a simple extension called User -- which is severely truncated for clarity. Notice I am defining const variables AND methods to use them.

classUserextendsBitwiseFlag{

constFLAG_REGISTERED=1;// BIT #1 of $flags has the value 1constFLAG_ACTIVE=2;// BIT #2 of $flags has the value 2constFLAG_MEMBER=4;// BIT #3 of $flags has the value 4constFLAG_ADMIN=8;// BIT #4 of $flags has the value 8public functionisRegistered(){

return$this->isFlagSet(self::FLAG_REGISTERED);

}

public functionisActive(){

return$this->isFlagSet(self::FLAG_ACTIVE);

}

public functionisMember(){

return$this->isFlagSet(self::FLAG_MEMBER);

}

public functionisAdmin(){

return$this->isFlagSet(self::FLAG_ADMIN);

}

public functionsetRegistered($value){$this->setFlag(self::FLAG_REGISTERED,$value);

}

public functionsetActive($value){$this->setFlag(self::FLAG_ACTIVE,$value);

}

public functionsetMember($value){$this->setFlag(self::FLAG_MEMBER,$value);

}

public functionsetAdmin($value){$this->setFlag(self::FLAG_ADMIN,$value);

}

public function__toString(){

return'User ['.

($this->isRegistered() ?'REGISTERED':'') .

($this->isActive() ?' ACTIVE':'') .

($this->isMember() ?' MEMBER':'') .

($this->isAdmin() ?' ADMIN':'') .']';

}

}?>

This seems like a lot of work, but we have addressed many issues, for example, using and maintaining the code is easy, and the getting and setting of flag values make sense. With the User class, you can now see how easy and intuitive bitwise flag operations become.

<?phprequire ('User.php')$user= newUser();$user->setRegistered(true);$user->setActive(true);$user->setMember(true);$user->setAdmin(true);

echo$user;// outputs: User [REGISTERED ACTIVE MEMBER ADMIN]?>

Anonymous (2011-10-12 07:56:00)

To make very clear why ("18" & "32") is "10".

1) they they are both strings ,

2) "&" operator works on strings by taking each !Character! from each string and make a bit wise & between them and add this value to the resulting string

So:

"18" is made up of two characters: 0x31, 0x38

"32" is made up of two characters: 0x33, 0x32

----RESULT-----

0x31 & 0x33 = 0x31 => "1"

0x38 & 0x32 = 0x30 => "0"

and the result is "10" which is 100% correct.

spencer-p-moy at example dot com (2011-09-17 18:21:14)

The NOT or complement operator ( ~ ) and negative binary numbers can be confusing.

~2 = -3 because you use the formula ~x = -x - 1 The bitwise complement of a decimal number is the negation of the number minus 1.

NOTE: just using 4 bits here for the examples below but in reality PHP uses 32 bits.

Converting a negative decimal number (ie: -3) into binary takes 3 steps:

1) convert the positive version of the decimal number into binary (ie: 3 = 0011)

2) flips the bits (ie: 0011 becomes 1100)

3) add 1 (ie: 1100 + 0001 = 1101)

You might be wondering how does 1101 = -3. Well PHP uses the method "2's complement" to render negative binary numbers. If the left most bit is a 1 then the binary number is negative and you flip the bits and add 1. If it is 0 then it is positive and you don't have to do anything. So 0010 would be a positive 2. If it is 1101, it is negative and you flip the bits to get 0010. Add 1 and you get 0011 which equals -3.

aba at example dot com (2011-08-12 05:07:51)

It is true that if both the left-hand and right-hand parameters are strings, the bitwise operator will operate on the characters' ASCII values. However, a complement is necessary to complete this sentence.

It is not irrelevant to point out that the decimal character's ASCII value have different binary values.

echoord('18');//return decimal value 49, which have binary value 110001echoord('32');//return decimal value 51, which have binary value 110011echoord('10');//return decimal value 49, which have binary value 110001

//Therefore 110001 & 110011 = 110001}?>

Anonymous (2011-07-31 04:33:24)

Using stings will just use every byte of the string - which is for me not unexpected at all:

// 49& 51== 49, 56& 50== 48

// chr( 49 )== '1', chr( 48 )== '0'?>You have to typecast each operand to the data type you're expecting.

ivoras at gmail dot com (2011-06-06 04:44:14)

As an additional curiosity, for some reason the result of the operation ("18" & "32") is "10". In other words, try avoiding using the binary operators on strings :)

josh at joshstrike dot com (2011-02-11 19:54:41)

More referencing this for myself than anything... if you need to iterate through every possible binary combination where $n number of flags are set to 1 in a mask of $bits length:

functionmasksOf($n,$bits) {$u=pow(2,$bits)-1;//start value, full flags on.$masks= array();

while ($u>0) {$z=numflags($u);

if ($z==$n)array_push($masks,$u);$u--;

}

return ($masks);

}

functionnumflags($n) {$k=0;

while ($n) {$k+=$n&1;$n=$n>>1;

}

return ($k);//    alternately:

//    $u = 0;

//    for ($k=1;$k<=$n;$k*=2) {

//        $u+=($n&$k?1:0);

//    }

//    return ($u);}?>

amckenzie4 at gmail dot com (2010-08-25 08:19:38)

If, like me, you've never thought about how PHP deals with binary, the output of the bitwise NOT may confuse you. For instance, this:

$bin = 2;

$notbin = ~$bin;

echo "Bin: " . decbin($bin) . " !bin: " . decbin($notbin) . "\n";

returns this:

Bin: 10 !bin: 1111111111111111111111111111111111111111111111111111111111111101

The reason is that all binary numbers are treated as 32 bits, even if you've manually entered less. In order to get the result I expected (01), it was necessary to AND the result with the number of bits I wanted: in this case, 2 (the number 3, in decimal). Be aware that all return values will have zeros removed from the left until they reach a bit that is set to 1. Continuing the above example, the following:

$notbin_2 = ~$bin & '3';

echo "!bin & 3: " . decbin($notbin_2) . "\n";

returns this:

!bin & 3: 1

Note that the actual value was a string of 31 zeros followed by a 1, but the zeros were not shown. This is probably a good thing.

Furthermore, the NOT operator uses two's complement, which means the number you get may be even stranger than you expect: using two's complement means that ~2 == -3. There are plenty of good explanations of two's complement online, so I won't go into that question here.

If what you want is just to reverse a string of bits without any interpretation, you can use a function like this:

function bitnot($bin)

{

$not = "";

for ($i = 0; $i < strlen($bin); $i++)

{

if($bin[$i] == 0) { $not .= '1'; }

if($bin[$i] == 1) { $not .= '0'; }

}

return $not;

}

It takes a binary string of any length, reverses the bits, and returns the new string. You can then treat it as a binary number, use bindec() to turn it into a decimal, or whatever you want.

I hope this helps someone as much as it would have helped me a week ago!

Core Xii (2010-08-11 10:24:29)

Be very careful when XOR-ing strings! If one of the values is empty (0, '', null) the result will also be empty!

var_dump(1234^0);// int(1234)var_dump(1234^'');// int(1234)var_dump(1234^null);// int(1234)var_dump('hello world'^0);// int(0)var_dump('hello world'^'');// string(0) ""var_dump('hello world'^null);// int(0)?>

This seems rather inconsistent behavior. An integer XOR'd with zero results the original integer. But a string XOR'd with an empty value results an empty value!

My password hashing function was always returning the same hash... Because I was XOR-ing it with a salt that was sometimes empty!

steffen at NO-SPAM dot haugk dot co dot uk (2010-07-20 03:23:26)

It says above that the effect of

E_ALL & ~E_NOTICE

can also be achieved by

E_ALL ^ E_NOTICE

NB: XOR is not equivalent to AND NOT.

This only works here because E_ALL consists of 1s mostly, with the exception of the bit for E_STRICT.

As E_ALL means all error levels apart from E_STRICT. XORing any error level switches it off, but XORing E_STRICT will switch it on.

E_ALL ^ E_NOTICE : E_NOTICE switched off

E_ALL ^ E_STRICT : E_STRICT switched on

E_ALL & ~E_NOTICE : E_STRICT switched off

E_ALL & ~E_STRICT : E_STRICT remains switched off

Adam (2010-05-15 13:25:30)

Be careful of order of operations.

for example, you may want to check if the second bit is set:

is different than

and the latter of the two should be used.

Anonymous (2010-01-12 10:18:34)

Beware that PHP's <> operators, unlike the other bitwise operators do not work on ASCII values; <> cast their operands to integer (when possible) before shifting and will always return an integer result.

For example:

$foo="1";// chr(49)var_dump($foo<<1);// Output is int(2)$foo="!";// chr(33)var_dump($foo<<1);// Output is int(0)?>

Alex (2009-11-11 10:10:36)

Okay, I'm twelve, and I am new to PHP, but I created the following -simple- functions:

if(round($num)==$num) {

returnfalse;

}

else {

returntrue;

}

}

functiondecshiftl($number,$amount){

if(Isdec($number)) {$decimal=substr($number, (strlen($number) -round($number) +1));$decimal*=pow(10,strlen($decimal) -1);$Shiftl= ($number<

}

else {$Shiftl=$number<

}

return$Shiftl;

}

functiondecshiftr($number,$amount){

if(Isdec($number)) {$decimal=substr($number, (strlen($number) -round($number) +1));$decimal*=pow(10,strlen($decimal) -1);$Shiftr= ($number>>$amount) + (($decimal>>$amount) /pow(10,strlen($decimal)));

}

else {$Shiftr=$number>>$amount;

}

return$Shiftr;

}?>Anyway, it's just shoving parameters in to an equation, but sometimes reinventing the wheel and putting rockets on it is a good thing.

zooly at globmi dot com (2009-10-19 07:52:48)

Here is an example for bitwise leftrotate and rightrotate.

Note that this function works only with decimal numbers - other types can be converted with pack().

return (bindec(substr($binary,$bits).substr($binary,0,$bits))

);

}// Rotate 124 (1111100) to the left with 1 bitsechorotate(124,1);// = 121 (1111001)

// Rotate 124 (1111100) to the right with 3 bitsechorotate(124, -3);// = 79 (1001111)?>

grayda dot NOSPAM at DONTSPAM dot solidinc dot org (2009-06-03 20:48:55)

Initially, I found bitmasking to be a confusing concept and found no use for it. So I've whipped up this code snippet in case anyone else is confused:

And you can apply this to a lot of things, for example, security:

if($user&$permission) {

returntrue;

} else {

returnfalse;

}

}// Now we apply all of this!if(checkPermission($administrator,$deleteUser)) {deleteUser("Some User");# This is executed because $administrator can $deleteUser}?>

Once you get your head around it, it's VERY useful! Just remember to raise each value by the power of two to avoid problems

Silver (2009-05-12 16:36:17)

Regarding what Bob said about flags, I'd like to point out there's a 100% safe way of defining flags, which is using hexadecimal notation for integers:

define("f0",0x1);// 2^0define("f1",0x2);// 2^1define("f2",0x4);// 2^2define("f3",0x8);// 2^3define("f4",0x10);// 2^4define("f5",0x20);// 2^5

// ...define("f20",0x1000000);// 2^20define("f21",0x2000000);// 2^21define("f22",0x4000000);// 2^22define("f23",0x8000000);// 2^23define("f24",0x10000000);// 2^24

// ... up to 2^31?>

I always avoid using decimal notation when I have a large amount of different flags, because it's very easy to misspell numbers like 2^20 (1048576).

Bob (2009-04-26 00:19:57)

Here is an easy way to use bitwise operation for 'flag' functionality.

By this I mean managing a set of options which can either be ON or OFF, where zero or more of these options may be set and each option may only be set once. (If you are familiar with MySQL, think 'set' datatype).

Note: to older programmers, this will be obvious.

Here is the code:

{$val=0;

foreach(func_get_args() as$flag)$val=$val|$flag;

return$val;

}

functionis_bitflag_set($val,$flag)

{

return (($val&$flag) ===$flag);

}// Define your flagsdefine('MYFLAGONE',1);// 0001define('MYFLAGTWO',2);// 0010define('MYFLAGTHREE',4);// 0100define('MYFLAGFOUR',8);// 1000?>

I should point out: your flags are stored in a single integer. You can store loads of flags in a single integer.

To use my functions, say you wanted to set MYFLAGONE and MYFLAGTHREE, you would use:

$myflags=set_bitflags(MYFLAGONE,MYFLAGTHREE);?>Note: you can pass set_bitflags() as many flags to set as you want.

When you want to test later if a certain flag is set, use e.g.:

{

echo"MYFLAGTWO is set!";

}?>

The only tricky part is defining your flags. Here is the process:

1.  Write a list of your flags

2.  Count them

3.  Define the last flag in your list as 1 times 2 to the power of  minus one. ( I.E. 1*2^(-1) )

3. Working backwards through your list, from the last to the first, define each one as half of the previous one. You should reach 1 when you get to the first

If you want to understand binary numbers, bits and bitwise operation better, the wikipedia page explains it well - http://en.wikipedia.org/wiki/Bitwise_operation.

cw3theophilus at gmail dot com (2009-04-15 14:22:44)

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.)

<?phpfunctioncircular_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 valuesif ($offset>0) {$num=($num<>(32-$offset%32)) & ($mask>>(31-$offset%32)));

}

elseif ($offset<0){$offset=abs($offset);$num=(($num>>$offset%32) & ($mask>>(-1+$offset%32))) | ($num<

}

return$num;

}?>

m0sh at hotmail dot com (2008-08-07 00:03:20)

@greenone - nice function, thanks. I've adapted it for key usage:

for($i=0;$i

return$res;

}?>

bartbons at debster.nl (2008-04-07 02:27:55)

@kendsnyder at gmail dot com

Thanx for your great function. But your function is not 100% correct. It should be:

function safeBitCheck($number,$comparison) {

if( $number < 2147483647 ) {

return ($number & $comparison)==$comparison;

} else {

$binNumber = strrev(base_convert($number,10,2));

$binComparison = strrev(base_convert($comparison,10,2));

for( $i=0; $i

if( strlen($binNumber) - 1

return false;

}

}

return true;

}

}

Mind the 'minus 1' on "if( strlen($binNumber) - 1

cheers, Bart

forlamp at msn dot com (2007-12-06 18:35:50)

two's complement logical operation for 32-bit.

$x must be (int) when passing it to this function to work properly.

function comp2($x) // 32bit bitwise complement

{

$mask = 0x80000000;

if ($x < 0)

{

$x &= 0x7FFFFFFF;

$x = ~$x;

return $x ^ $mask;

}

else

{

$x = $x ^ 0x7FFFFFFF;

return $x | $mask;

}

}

Visual (2007-06-20 06:42:28)

To perform bitwise operations on floats, or anything for that matter, in the binary representation of your choice, simply use pack() on the data with the appropriate parameters, then you can operate on the resulting strings. in the end just unpack()

gcG (2007-03-01 16:23:57)

function xnor($a, $b) {

return ~($a ^ $b);

}

XNOR is very usefull ;D

bryanagee at gmail dot com (2007-02-08 11:19:58)

I found the 31-bit limitation on the bitwise ands to be a bit frustrating in large scale permission control applications. I have a situation involving page-level access with more than 50 pages. I was able to workaround the limitation by adding a loop that dropped 31 bits off of the right until the resource identifier bit is within the first 31.

$userlevel=$session->userlevel-0;# the subtraction ensures int type$pg_code=pow(2,($pg_id-1));

while ($pg_code>=2147483648)  {$pg_code=$pg_code/pow(2,31);$userlevel=$session->userlevel/pow(2,31) ;

}

if (!($userlevel-0&$pg_code)) {#if not authorized, show the unauthorized pageheader('Location: Unauthorized.php');

exit;

}?>

zewt at hotmail dot com (2007-01-11 23:28:46)

if you use bitwise you MUST make sure your variables are integers, otherwise you can get incorrect results.

I recommend ALWAYS

(int)$var & (int)$var2

This will save you many headaches when troubleshooting a completely illogical result.

rizal dot almashoor at gmail dot com (2006-11-13 16:12:50)

The following function will perform a 32-bit left shift on a 64-bit machine:

{$binary=decbin($number).str_repeat("0",$steps);$binary=str_pad($binary,32,"0",STR_PAD_LEFT);$binary=substr($binary,strlen($binary) -32);

return$binary{0} =="1"? -(pow(2,31) -bindec(substr($binary,1))) :bindec($binary);

}?>

Xavier Daull (2006-02-04 13:34:37)

{// 1. Create a bit mask of the right size by triming left and right

// 2. select bits by an AND on $mybindata

// 3. shift right to get only length neededif($highestbitfirst) return (((0x7FFFFFFF>> (30+$lastbit-$firstbit))<> ($lastbit);

else return (((0x7FFFFFFF>> (30-$lastbit+$firstbit))<> (30-$lastbit);

}?>

John L (2006-02-02 14:11:39)

Bitwise operators are swell, but (a & b & c & d) == a

is not a way to test for four-way equality. If a is zero, it'll always be true, and in general it will be true any time a has no bits not also in the other three values.

Nina Cording (2005-10-29 09:50:03)

For those who were searching for a way to actually rotate the bits of a number, here are some little functions I wrote:

if ($amount>0) {$amount%=32;$value= ($value<>(32-$amount));

} elseif ($amount<0) {$amount= -$amount%32;$value= ($value>>$amount) | ($value<

}

return$value;

}

functionbitRotate($value,$amount,$bits) {$mask= ($bits<32) ?0x7fffffff>> (31-$bits) :0xffffffff;

if ($amount>0) {$amount%=$bits;$value= ($value<>($bits-$amount));

} elseif ($amount<0) {$amount= -$amount%$bits;$value= ($value>>$amount) | ($value<

}

return$value&$mask;

}// test the rotation:$test=4123;

for ($i=0;$i<64;$i++) {$value=bitRotate($test,-$i,8);// rotates 8 bits to the left (-$amount)echosprintf("%032b
",$value);

}?>

zlel grxnslxves13 at hotmail dot com~=s/x/ee/g (2005-10-26 19:30:45)

I refer to Eric Swanson's post on Perl VS PHP's implementation of xor.

Actually, this is not an issue with the implementation of XOR,  but a lot more to do with the lose-typing policy that PHP adopts.

Freely switching between int and float is good for most cases, but problems happen when your value is near the word size of your machine. Which is to say, 32-bit machines will encounter problems with values that hover around 0x80000000 - primarily because PHP does not support unsigned integers.

using bindec/decbin would address this issue as a work-around to do unsigned-int xor, but here's the real picture (i'm not claiming that this code will perform better, but this would be a better pedagogical code):

{$a1=$a&0x7FFF0000;$a2=$a&0x0000FFFF;$a3=$a&0x80000000;$b1=$b&0x7FFF0000;$b2=$b&0x0000FFFF;$b3=$b&0x80000000;$c= ($a3!=$b3) ?0x80000000:0;

return (($a1^$b1) |($a2^$b2)) +$c;

}$x=3851235679;$y=43814;

echo"
This is the value we want";

echo"
3851262585";

echo"
The result of a native xor operation on integer values is treated as a signed integer";

echo"
".($x^$y);

echo"
We therefore perform the MSB separately";

echo"
".unsigned_xor32($x,$y);?>

This is really foundation stuff, but for those of you who missed this in college, there seems to be something on 2's complement here:

http://www.evergreen.edu/biophysics/technotes/program/2s_comp.htm

zlel (2005-10-26 17:22:06)

Here're my 32-bit carry-discarding operations for those of you porting encryption algorithms from C.

Be warned that some of these are not very efficient compared to the native operations, especially when called by heavy-duty encryption algorithms - but not discarding the carry bit may not land you the same results you get in C, simply because PHP's bitwise operations were not designed to work on fixed-sized registers.

(If your ported encryption algo still doen't give you the same results, remember to check your Endian-ness!)

function _BF_SHR32 ($x, $bits)

{

if ($bits==0) return $x;

if ($bits==32) return 0;

$y = ($x & 0x7FFFFFFF) >> $bits;

if (0x80000000 & $x) {

$y |= (1<

}

return $y;

}

function _BF_SHL32 ($x, $bits)

{

if ($bits==0) return $x;

if ($bits==32) return 0;

$mask = (1<

return (($x & $mask) << $bits) & 0xFFFFFFFF;

}

function _BF_GETBYTE ($x, $y)

{

return _BF_SHR32 ($x, 8 * $y) & 0xFF;

}

function _BF_OR32 ($x, $y)

{

return ($x | $y) & 0xFFFFFFFF;

}

function _BF_ADD32 ($x, $y)

{

$x = $x & 0xFFFFFFFF;

$y = $y & 0xFFFFFFFF;

$total = 0;

$carry = 0;

for ($i=0; $i<4; $i++) {

$byte_x = _BF_GETBYTE($x, $i);

$byte_y = _BF_GETBYTE($y, $i);

$sum = $byte_x + $byte_y;

$result = $sum & 0xFF;

$carryforward = _BF_SHR32($sum, 8);

$sum = $result + $carry;

$result = $sum & 0xFF;

$carry = $carryforward + _BF_SHR32($sum, 8);

$total = _BF_OR32(_BF_SHL32($result, $i*8), $total);

}

return $total;

}

Tbrendstrup (2005-09-29 05:23:56)

note that the shift operators are arithmetic, not logic like in C. You may get unexpected results with negative numbers, see http://en.wikipedia.org/wiki/Bitwise_operation

here's a function to do logic right shifts.

{$mask=0x40000000;

if($var<0)

{$var&=0x7FFFFFFF;$mask=$mask>> ($amt-1);

return ($var>>$amt) |$mask;

}

return$var>>$amt;

}$val= -10;printf("arithmetic shift on a negative integer
%1\$032b
%2\$032b
%1\$0d
%2\$0d
",$val,$val>>1);printf("logic shift on a negative integer
%1\$032b
%2\$032b
%1\$0d
%2\$0d
",$val,lshiftright($val,1));printf("logic shift on a positive integer
%1\$032b
%2\$032b
%1\$0d
%2\$0d
",-$val,lshiftright(-$val,1));?>

gives the output:

arithmetic shift on a negative integer

11111111111111111111111111110110

11111111111111111111111111111011

-10

-5

logic shift on a negative integer

11111111111111111111111111110110

01111111111111111111111111111011

-10

2147483643

logic shift on a positive integer

00000000000000000000000000001010

00000000000000000000000000000101

10

5

Eric Swanson (2005-08-31 17:19:38)

Perl vs. PHP implementation of the ^ operator:

After attempting to translate a Perl module into PHP, I realized that Perl's implementation of the ^ operator is different than the PHP implementation. By default, Perl treats the variables as floats and PHP as integers. I was able to verify the PHP use of the operator by stating "use integer;" within the Perl module, which output the exact same result as PHP was using.

The logical decision would be to cast every variable as (float) when using the ^ operator in PHP. However, this will not yield the same results. After about a half hour of banging my head against the wall, I discovered a gem and wrote a function using the binary-decimal conversions in PHP.

/*

not having much experience with bitwise operations, I cannot tell you that this is the BEST solution, but it certainly is a solution that finally works and always returns the EXACT same result Perl provides.

*/

function binxor($a, $b) {

return bindec(decbin((float)$a ^ (float)$b));

}

//normal PHP code will not yeild the same result as Perl

$result = 3851235679 ^ 43814; //= -443704711

//to get the same result as Perl

$result = binxor(3851235679, 43814); //= 3851262585

//YIPPEE!!!

//to see the differences, try the following

$a = 3851235679 XOR 43814;

$b = 3851235679 ^ 43814; //integer result

$c = (float)3851235679 ^ (float)43814; //same as $b

$d = binxor(3851235679, 43814); //same as Perl!!

echo("A: $a
");

echo("B: $b
");

echo("C: $c
");

echo("D: $d
");

(2005-04-19 07:28:19)

Another practical case...

header('Content-Type: text/plain') ;// We want to know the power-2 based numbers of $x$x=9124;$n=1;

while ($x>0) {

if ($x&1==1) {

echo$n,"\n";

}$n*=2;$x>>=1;

}// Will output...

// 4

// 32

// 128

// 256

// 512

// 8192?>

(2005-03-04 15:13:40)

A bitwise operators practical case :

<?php // We want to know the red, green and blue values of this color :$color=0xFEA946;$red=$color>>16;$green= ($color&0x00FF00) >>8;$blue=$color&0x0000FF;printf('Red : %X (%d), Green : %X (%d), Blue : %X (%d)',$red,$red,$green,$green,$blue,$blue) ;// Will display...

// Red : FE (254), Green : A9 (169), Blue : 46 (70)?>

icy at digitalitcc dot com (2005-02-23 23:24:29)

Say... you really want to have say... more than 31 bits available to you in your happy bitmask. And you don't want to use floats. So, one solution would to have an array of bitmasks, that are accessed through some kind of interface.

Here is my solution for this: A class to store an array of integers being the bitmasks. It can hold up to 66571993087 bits, and frees up unused bitmasks when there are no bits being stored in them.

Infinite* bits and bit handling in general.

*Not infinite, sorry.

Perceivably, the only limit to the bitmask class in storing bits would be

the maximum limit of the index number, on 32 bit integer systems 2^31 - 1,

so 2^31 * 31 - 1 = 66571993087 bits, assuming floats are 64 bit or something.

I'm sure that's enough enough bits for anything.. I hope :D.

*/DEFINE('INTEGER_LENGTH',31);// Stupid signed bit.classbitmask{

protected$bitmask= array();

public functionset($bit)// Set some bit{$key= (int) ($bit/INTEGER_LENGTH);$bit= (int)fmod($bit,INTEGER_LENGTH);$this->bitmask[$key] |=1<

}

public functionremove($bit)// Remove some bit{$key= (int) ($bit/INTEGER_LENGTH);$bit= (int)fmod($bit,INTEGER_LENGTH);$this->bitmask[$key] &= ~ (1<

if(!$this->bitmask[$key])

unset($this->bitmask[$key]);

}

public functiontoggle($bit)// Toggle some bit{$key= (int) ($bit/INTEGER_LENGTH);$bit= (int)fmod($bit,INTEGER_LENGTH);$this->bitmask[$key] ^=1<

if(!$this->bitmask[$key])

unset($this->bitmask[$key]);

}

public functionread($bit)// Read some bit{$key= (int) ($bit/INTEGER_LENGTH);$bit= (int)fmod($bit,INTEGER_LENGTH);

return$this->bitmask[$key] & (1<

}

public functionstringin($string)// Read a string of bits that can be up to the maximum amount of bits long.{$this->bitmask= array();$array=str_split(strrev($string),INTEGER_LENGTH);

foreach($arrayas$key=>$value)

{

if($value=bindec(strrev($value)))$this->bitmask[$key] =$value;

}

}

public functionstringout()// Print out a string of your nice little bits{$string="";$keys=array_keys($this->bitmask);sort($keys,SORT_NUMERIC);

for($i=array_pop($keys);$i>=0;$i--)

{

if($this->bitmask[$i])$string.=sprintf("%0".INTEGER_LENGTH."b",$this->bitmask[$i]);

}

return$string;

}

public functionclear()// Purge!{$this->bitmask= array();

}

public functiondebug()// See what's going on in your bitmask array{var_dump($this->bitmask);

}

}?>

It treats a positive integer input as a bit, so you don't have to deal with the powers of 2 yourself.

$bitmask= newbitmask();$bitmask->set(8979879);// Whatever$bitmask->set(888);

if($bitmask->read(888))

print'Happy!\n';$bitmask->toggle(39393);// Yadda yadda$bitmask->remove(888);$bitmask->debug();$bitmask->stringin("100101000101001000101010010101010

00000001000001");

print$bitmask->stringout() ."\n";$bitmask->debug();$bitmask->clear();$bitmask->debug();?>

Would produce:

Happy!

array(2) {

[289673]=>

int(65536)

[1270]=>

int(8388608)

}

0000000000000001001010001010010001010100101010100

0000001000001

array(2) {

[0]=>

int(355106881)

[1]=>

int(37970)

}

array(0) {

}

louis /at/ mulliemedia.com (2005-01-20 14:12:22)

Note that the ^ operator, unlike in some other languages, is *not* the same as the pow() function.

richard-slater.co.uk (2004-02-22 01:07:20)

For those (like me) who are trying to do bit masking with very large numbers, here is a useful function to do the work for you.

{

return (bool)gmp_intval(gmp_div(gmp_and($bitMask,$bitMap),$bitMask));

}?>

krang at krang dot org dot uk (2003-12-04 14:30:08)

Hopefully this may help someone understand the fun of Bitwise Operators....

The purpose of this function is to return a value from the GPC (Get, Post and Cookie) and do some basic formatting to it depending on the $VALIDATION value:

// Get the value from the

// relevant submit method...if ($METHOD=='POST') {

if (!isset($_POST[$VARIABLE]))$_POST[$VARIABLE] ='';$VALUE=$_POST[$VARIABLE];

} elseif ($METHOD=='COOKIE') {

if (!isset($_COOKIE[$VARIABLE]))$_COOKIE[$VARIABLE] ='';$VALUE=$_COOKIE[$VARIABLE];

} else {

if (!isset($_GET[$VARIABLE]))$_GET[$VARIABLE] ='';$VALUE=$_GET[$VARIABLE];

}//-------------------------------

// If necessary strip the slashes.

// the "GPC" means - GET, POST

// COOKIE.if (ini_get('magic_quotes_gpc') ==true) {$VALUE=stripslashes($VALUE);

}//-------------------------------

// Now for the different types

// of VALIDATION'sif (($VALIDATION&8) ==8) {$VALUE= (int)$VALUE;

}

if (($VALIDATION&4) ==4) {$VALUE=strtolower($VALUE);

}

if (($VALIDATION&2) ==2) {$VALUE=strip_tags($VALUE);

}

if (($VALIDATION&1) ==1) {$VALUE=trim($VALUE);

}//-------------------------------

// Finally return the valuereturn$VALUE;

}

echoRETURN_SUBMITTED_VALUE('ID','GET',8) .'
';// Convert to an IntegerechoRETURN_SUBMITTED_VALUE('NAME','GET',3) .'
';// Trim Whitespace and Strip HTML tagsechoRETURN_SUBMITTED_VALUE('GENDER','GET',6) .'
';// Strip HTML tags and convert to lower case

//-----------------------------------------------

// If this script was loaded under the URL

// index.php?ID=19a&NAME=Krang&GENDER=MalE

// it would print

//

// 19

// Krang

// male

//-----------------------------------------------?>

For those that don?t understand binary, the numbers you see are not random, they double each time (1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024...) which allows you to mix and match the different function, eg...

1 + 2 = 3 (Trim Whitespace + Strip HTML)

2 + 4 = 6 (Strip HTML + Convert to lower case)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值