doupu7651 2013-02-01 13:53
浏览 24
已采纳

&作为PHP中的算术运算符[重复]

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

I am working on some legacy code where I came across the following function:

function is_odd($number) {
   return $number & 1; // 0 = even, 1 = odd
}

I have never seen a method to check if a number is odd written like that before and am just trying to understand what they actually are doing.

  • 写回答

1条回答 默认 最新

  • dqq9695 2013-02-01 13:59
    关注

    & is a bitwise-and, it basically works so that for every bit that is 1 in both operands, it yields 1 in the resulting value and 0 for all other bits. If you convert any number to its bit representation, you quickly see that it's the lowest bit that determines whether a number is even or odd, for example:

       5 = 101
      10 = 1010
      13 = 1101
    1030 = 10000000110
    

    The lowest bit (the one on the very right, also called the least significant bit) is 1 for every odd number and 0 for every even number. Doing $n & 1 will always yield 0 for every other bit than the lowest bit (because the number 1 only has one bit, you can imagine that the rest of the bits are left-padded with 0 to match the length of the other operand). So basically the operation boils down to comparing the lowest bit of the operands, and 1 & 1 is 1, all other combinations are 0. So basically when the $n & 1 yields 1, it means the number is odd, otherwise it's even.

    EDIT.

    Here's a few examples to demonstrate how the bitwise-and works for the example values I gave earlier, the number in the parenthesis is the original decimal number:

      101 (5)
    & 001 (1)
      ---
      001 (1) = true
    
    
      1010 (10)
    & 0001 (1)
      ----
      0000 (0) = false
    
    
      1101 (13)
    & 0001 (1)
      ----
      0001 (1) = true
    
    
      10000000110 (1030)
    & 00000000001 (1)
      -----------
      00000000000 (0) = false
    

    From this you can easily see that the result is only true when both operands' right-most bits are 1.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?