0

Possible Duplicate:
Reference - What does this symbol mean in PHP?

I was searching for a password generator tutorial, which I found one but somethings got me a little confused...

if ($strength & 2) {
$vowels .= "AEIOU";
}

What exactly is this operator? I know && equals "and" but just one &?

Community
  • 1
  • 1
David Lawrence
  • 639
  • 1
  • 8
  • 13

4 Answers4

2

That is called a bitwise operator. Learn more.

Alex R.
  • 4,394
  • 4
  • 28
  • 40
0

It's the bitwise and.

Zach Johnson
  • 21,761
  • 6
  • 66
  • 83
0

As in most programming languages, & is the bitwise and operator. x & 2 tests whether the second (least significant) bit of x is set (2 is 10 in binary).

Jan Pöschko
  • 4,786
  • 24
  • 24
  • Yes, except in VB.Net (and earlier VB's if I remember correctly), in which case it's the string concatenation operator. – Kibbee Dec 19 '11 at 01:46
  • So how in this way is $strength being tested? Cause its testing 1, 2, 4, and 8.. What do the 1 2 4 and 8 mean? – David Lawrence Dec 19 '11 at 01:48
  • Which you wouldnt know that cause some dude removed half my damn question cause its "possibly" a duplicate.. – David Lawrence Dec 19 '11 at 01:49
  • @David they are powers of two, which are 0001, 0010, 0100, and 1000 in binary, respectively. – Zach Johnson Dec 19 '11 at 01:50
  • @Zach Thanks bud.. Still dont understand it but ill just echo or print_r every step of the function till i do.. – David Lawrence Dec 19 '11 at 01:52
  • @David: from my cursory glance at the code that was edited out, it looks like the person who wrote that code is using $strength as a bitwise flag variable. – Zach Johnson Dec 19 '11 at 01:54
  • @Zach yea the code that was there wouldve helped quite a few people answer the follow up questions i had. Was really annoying that it was removed. Thanks again – David Lawrence Dec 19 '11 at 01:56
  • Testing against 1, 2, 4, and 8 means asking whether the first, second, third, and fourth bit of `$strength` are set. – Jan Pöschko Dec 19 '11 at 01:58
  • OHHHHHHHHHHHHHHHHHHHHHHHH Ok so 8 would mean that hte 4th bit is set, and 4 would be third and so on! OK! I get it now. Thanks! Btw do bits go higher than 4? Like if i did 16 wouldnt that mean that the 8th bit would be set? – David Lawrence Dec 19 '11 at 02:05
  • `x & 16` would test for the fifth bit (`16 = 2 ^ 4 = 10000` in binary). Of course, higher bits can be tested accordingly. Usually, integers have a size of 32 bit (signed). – Jan Pöschko Dec 19 '11 at 02:15
0

& is the bitwise AND operator. It sets bits that are in both numbers that are tested.

Example: 6 & 4

6 ->     1 1 0
4 ->     1 0 0

6 & 4 -> 1 0 0 -> 4
6 & 4 = 4

Example: 13 & 10

13 ->     1 1 0 1
10 ->     1 0 1 0

13 & 9 -> 1 0 0 0 -> 8
13 & 9 = 8
Will
  • 17,297
  • 7
  • 45
  • 48