I have a question about bit operation in c++,
there is a set of code:
#define INDEX(SRC, DEST) ((U16)SRC | (DEST << 8))
what does this (U16)SRC | (DEST << 8)
(U16)SRC | (DEST << 8)
means?
(U16)SRC
casts SRC
to be of type U16
. (DEST << 8)
does a bitwise shift left of 8 bits. |
operator performs bitwise OR
. 它将SRC
转换为U16
类型,并在向左移动(8)个位置后与DEST
进行按位“或”运算。
I would guess U16 is also a macro somewhere in the code and it probably designates a 16-bit unsigned integer type(which I deduce from the abbreviation). SRC and DST are the two arguments to the macro expansion the code is defining and (U16)SRC | (DEST << 8) would mean that DEST gets bit shifted 8 bits to the left and then logical or-ed to SRC. Probably the code depends that both SRC and DEST are 8-bit values and this code creates a bit mask that is the result of the appending of the 8-bits of DEST to the 8-bits of SRC.
For instance if (in binary) DEST is 10010101 and SRC is 00001111 then the result is 1001010100001111.
With the code you showed it is a lot of guessing: sure, it looks as if U16
is a macro for unsigned short
or uint16_t
. If you want to find out, what the define expands to include the definition of the the macro and invoke the macro in a simple test program:
#include "whatever-defines-INDEX.h"
INDEX(10, 1)
Then invoke the compiler with the -E
option (or the /E
option if -E
isn't available and you are using Windows): this sends the result of running the preprocessor to the standard output.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.