search

Home  >  Q&A  >  body text

c++ - 位运算符中不明白的地方

对于形如value = value | 1 << bit_number的表达式,目的是将指定位设为1。

不明白的是:此表达式运算符优先级|大于<<吗,要是这样的话,例如:value为01011100,bit_number为3,可是计算之后很多位发生了变化,感觉不太对。那要是<<优先级大于|,那么先将bit_number左移一位,再进行或操作,感觉也是好多为发生了变化。所以,关键点是指定位指的是哪几个位?

先谢谢了。

伊谢尔伦伊谢尔伦2804 days ago587

reply all(5)I'll reply

  • 迷茫

    迷茫2017-04-17 13:36:41

    First of all, << has a higher priority than |.

    Secondly, there is a mistake in your understanding: <<The right shift operator shifts the parameter on the left side of the operation to the right by the parameter position on the right side. In other words, 1 << bit_number does not shift bit_number to the right 1 bit, but shift 1 to the right by bit_number bit.
    Give your example, when bit_number is 3, the result of 1 << bit_number is 00001000. Then do the AND operation with value of 01011100, and you can change the 4 position from the right to 1.

    The designated position is a certain digit, which refers to the bit_number+1th digit

    from right to left.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 13:36:41

    http://jb51.net/article/37282.htm
    Priority

    reply
    0
  • 阿神

    阿神2017-04-17 13:36:41

    << has a higher priority than |. After the operation, only one bit of value will change at most.

    The function of this expression is to set the valueth of bit_number to 1.

    For example: value = 01010100, bit_number = 3, the result of the operation is (01010100 | 1000) = 01011100

    reply
    0
  • 迷茫

    迷茫2017-04-17 13:36:41

    1 << The bit_number is 0000 0001 (assumed to be 8 bits) and the bit_number bit is shifted to the left, rather than the bit_number is shifted to the left by one bit. If you are not familiar with the basic concept, let’s take a look at the basics first. . . .

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-17 13:36:41

    1. << has a higher priority than |.

    2. 1 << bit_number shifts 1 to the left by bit_number bits, so the result is a binary number containing only one 1 (its bit_number bit from right to left is 1). For example, 1 << 3 gets The binary number is 1000.

    3. will be used for bitwise AND operation with value in the future, and the effect should be clear at a glance.

    reply
    0
  • Cancelreply