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 基于作物生长模型下,有限水资源的最大化粮食产量的资源优化模型建立
  • ¥20 关于变压器的具体案例分析
  • ¥15 生成的QRCode圖片加上下載按鈕
  • ¥15 板材切割优化算法,数学建模,python,lingo
  • ¥15 科来模拟ARP欺骗困惑求解
  • ¥100 iOS开发关于快捷指令截屏后如何将截屏(或从截屏中提取出的文本)回传给本应用并打开指定页面
  • ¥15 unity连接Sqlserver
  • ¥15 图中这种约束条件lingo该怎么表示出来
  • ¥15 VSCode里的Prettier如何实现等式赋值后的对齐效果?
  • ¥20 keepalive配置业务服务双机单活的方法。业务服务一定是要双机单活的方式