I need some help understanding the follow functions & how they work.

1) y >> 16 & 0xFF0
2) (y >> 16 & 0xFFC) << 4
3) (y >> 20 & 0xF0F) | 1 << 7

Dani AI

Generated

Short summary and practical notes for the three bitwise expressions quoted in the OP.

  1. The first expression: shift the value right so higher-order bits move down, then mask off everything except the bits you want. 2) The second: do that extraction and then shift the extracted chunk back left to re-position it. 3) The third: extract a chunk and then combine it with a single-bit constant using bitwise OR — that sets the specified bit in the result (it does not XOR or compare). @WaltP was right to correct the XOR idea; @rubberman correctly noted that ^ is XOR and | is OR, and @nullptr’s concrete example of extraction shows the masking idea well.

Operator precedence explains why the grouping works without extra parentheses: shift operators are evaluated before the bitwise AND/OR, so the common pattern is "(shift) then (mask)" and the single-bit constant is computed with its shift before the OR. See the C++ operator precedence table for details: C++ operator precedence.

A couple of practical and safety tips:

  • Work with unsigned integers when shifting. Right-shifting signed negative values is implementation-defined; left shifts that overflow are undefined. Prefer uint32_t (from <cstdint>) and add u suffixes to literal masks.

  • Make intent explicit with parentheses and small, testable steps. For example:

    uint32_t u = static_cast<uint32_t>(y);
    uint32_t part = (u >> 8) & 0x0F0;
    uint32_t moved = part << 4;
    uint32_t final = moved | (1u << 3);

Quick bit-operation cheats: OR with a mask sets bits, XOR toggles bits, AND with the inverted mask clears bits. Use unit tests with known hex patterns to confirm the bit positions you expect.

Recommended Answers

All 5 Replies

What do you think they do? If you try to explain them, we'll tell you where you got it wrong.

well, from what I know, the
1st one is
shift y by 16 & 0xFF0

2nd is
shift y by 16 & 0xFFC then shift left by 4

3rd
shift y by 20 & 0xF0F then comparing with 1 using XOR & then shift left by 4

pls let me know if im wrong here

Correct on the first 2.
Wrong on last one. There's no compare and no XOR...

But what do they mean

Just using the first example:
y >> 16 & 0xFF0 // y is shifted right by 16 bits, then bitwise and with bitmask 0xFF0

e.g 0xBEEFC000 >> 16 = 0xBEEF
0xBEEF & 0xFF0 = 0xEE0

FWIW, the XOR operator is ^ as in (0xCAFEFACE ^ 0xECAFEFAC). The | symbol is the OR operator.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.