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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.