2

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) means?

4
  • dpx.googlecode.com/svn-history/r4/trunk/libdpx/… Commented Jan 3, 2012 at 14:18
  • SRC is typecast to (i guess) unsigned int (16bits wide), DEST is shifted 8 bits to the left (same as multiplying DEST by 256) and then the result undergoes an OR operation, so it's like ( SRC | ( DEST * 256 ) ) Commented Jan 3, 2012 at 14:23
  • 1
    It's not a very solid macro though. Calling this with INDEX(a,b&c) results in very interesting results if you don't anticipate what order the operators get executed in. Commented Jan 3, 2012 at 14:39
  • 3
    By the way, never write macros like this. It can give unexpected results if either argument is an expression (e.g INDEX(s1+s2,d1+d2)). In C++, you should nearly always use an inline function for something like this; if for some reason you have to use a macro, then make sure you put parentheses around every appearance of the macro arguments. Commented Jan 3, 2012 at 14:46

4 Answers 4

4
  • (U16)SRC casts SRC to be of type U16.
  • (DEST << 8) does a bitwise shift left of 8 bits.
  • The | operator performs bitwise OR.
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

It casts SRC to a U16 type and performs a bitwise OR with DEST after it has been left-shifted by (8) positions.

Comments

0

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 -Eoption (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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.