对于形如value = value | 1 << bit_number
的表达式,目的是将指定位设为1。
不明白的是:此表达式运算符优先级|
大于<<
吗,要是这样的话,例如:value
为01011100,bit_number
为3,可是计算之后很多位发生了变化,感觉不太对。那要是<<
优先级大于|
,那么先将bit_number
左移一位,再进行或操作,感觉也是好多为发生了变化。所以,关键点是指定位指的是哪几个位?
先谢谢了。
迷茫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+1
th digit
阿神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 value
th of bit_number
to 1.
For example: value = 01010100, bit_number = 3
, the result of the operation is (01010100 | 1000) = 01011100
迷茫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. . . .
大家讲道理2017-04-17 13:36:41
<<
has a higher priority than |
.
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.
will be used for bitwise AND operation with value
in the future, and the effect should be clear at a glance.