What is the meaning of the following expression in c++?
(variable1 | (variable2 << 8))
What is the meaning of it开发者_运维问答? And what does it represent?
It concatenates the two variables.
Suppose you have two chars, a
and b
. a|b<<8
shifts the b
8 bits to the left, |
sets every bit that is in a
or b
.
So in this example the result would be "ab
".
'a' is 97, 'b' is 98, so bitwise the following happens:
a: 01100001
b: 01100010
b<<8: 0110001000000000
a|b<<8: 0110001001100001
|
is Bitwise OR
<<
is Bitwise left shift operator
(variable1 | (variable2 << 8))
Left Shifts the variable2
(8 bit) by 8
and then OR
s the result with variable1
(8 bit), resulting output will combine two variables variable1
and variable2
to be represented as one variable(16 bit).
You might think of it as "concatenating" two variables in a bitwise fashion.
If:
x = 00000000 00001000 (16-bit binary)
y = 00000000 00100010 (16-bit binary)
Then:
(y << 8) = 00100010 00000000
x | (y << 8) = 00100010 00001000
What it actually means in the context of the code in which you found it is anybody's guess.
In actual fact, "concatenating" is not accurate if x
has any bits set in the most significant byte:
If:
x = 01000000 00001000 (16-bit binary)
y = 00000000 00100010 (16-bit binary)
Then:
(y << 8) = 00100010 00000000
x | (y << 8) = 01100010 00001000
If variable1
and variable1
are 8-bit values, then it combines them into a single 16-bit value.
It would make sense if both variables where bytes. In that case it would combine them into one larger variable, so that first come 8 bits of variable2 and then 8 bits of variable1.
In your code, the 8 least significant (rightmost) bits of variable1
are appended to the bits of variable2
from the right, with the bits of variable2
being shifted left by 8.
If denote the bits of variable1
as
xxxxxxxxxxxxxxxxxxxxxxxxwxxxxxxx
and the bits of variable2
as
yyyyyyyyzyyyyyyyyyyyyyyyyyyyyyyy
then expression
(variable1 | (variable2 << 8))
would result in
zyyyyyyyyyyyyyyyyyyyyyyywxxxxxxx
I don't know what you mean by "meaning" - but this is one variable being bitwise OR'ed with another variable which has been left-shifted by 8 bits (which you can think of as being multiplied by 256).
If both variable1
and variable
are less than 256, the statement is the same as variable1 + (variable2*256)
.
More generally though, |
is binary or and and <<
is left shift.
So if we start with:
variable1 = 321;
variable2 = 123;
The binary values would be:
variable1 => 0000 0001 0100 0001
variable2 => 0000 0000 0111 1011
Left shifting variable2
by 8 results in:
0111 1011 0000 0000
So variable1 | (variable2 << 8)
equals
0111 1011 0100 0001
Which is 32065. This is less than 31519 which is the result of (321 + (123 * 256)) because variable1
and variable2 << 8
have some bits in common.
精彩评论