Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Bitwise operators 1

Status
Not open for further replies.

southbeach

Programmer
Jan 22, 2008
879
US
I have stared at this and cannot fully understand it
Code:
echo 12 ^ 6
will return 10 and
Code:
echo 12 ^ 9
will return 5

I like to think that I am a fairly smart individual but this one has proved me wrong.

php.net defines this as being able to turn specific bits within a string ON/OFF ... What? Further, a "bit" of info on why/where would I need something like this please!

Can you please explain this in plain English?


--
SouthBeach
The good thing about not knowing is the opportunity to learn - Yours truly, 2008.
 
Its binary operations, and its actually very straight forward.

bits within a string ON/OFF
its actually not a string but a number. a binary number.

In your example 12 and 6 are represented in binary code as

1100 for 12
0110 for 6

The ^ operator or Xor compares both values. It uses the bits that are set to 1 in one or the other but not both of the numbers for the result.

1100
0110
----
[blue]1[/blue][red]0[/red][blue]10[/blue]
Since the second 1 is in both of them the operation ignores the value and sets it to 0.

The resulting number is the binary representation of the decimal number 10.

in the case of 12 and 9:

1100 = 12
1001 = 9
----
0101 = 5

The resulting number is the representation of the decimal number 5.








----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.
 
Thanks guys!!!

I get it now ... I totally missed the "binary" part of it and so was stuck looking at it as plain "text" or "numeric" strings.

For now, I do not see the value for (when to use them), but there is a chance that I will down the road!

--
SouthBeach
The good thing about not knowing is the opportunity to learn - Yours truly, 2008.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top