Jump to content

[SOLVED] Bitwise operators...


aeonsky

Recommended Posts

Even after reading the manual, I have no idea what they are used for and how they produce the result...

 

For example, this...

 

<?php

echo 'this' ^ 'that';
// Produces weird ASCII values

echo 8 ^ 9;
// Produces 1

echo ~'this';
// Produces weird ASCII values

echo 'this' | 'that';
// Produces 'thiw'

?>

 

Could someone explain the operators in more simpler terms?

Link to comment
https://forums.phpfreaks.com/topic/129654-solved-bitwise-operators/
Share on other sites

You need to understand binary for these to have any meaning to you whatsoever.  If you don't, I'd suggest pretending that these operators don't exist, but if you want an explanation anyway:

 

Numbers are represented in computers as binary, which is a base 2 system, as opposed to our base 10 decimal system.  This means that the numbers 1, 2, 5, and 128 are represented, for example, like so:

1
10
101
1111111

The bitwise operators operate on each of those bits, or digits, as their own sort of unit.

 

The AND operator (&) returns bits that are set in both numbers.  Using my previous examples, this:

2 & 1

Would give you a result of 3, because the operator works like this:

[pre]

    10

+    1

------

    11

[/pre]

 

The OR (|) operator does the same thing, only it returns bits that are set in either number.

xor (^) only returns ones set in ONE number, but not the other, and NOT (~) flips every bit.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.