Search code examples
c++emulationbitwise-operatorsbit-shift

Why would you perform a Bit-shift twice ((x >> 4) << 4)?


So I am analyzing a Nes-Emulator code and I've come across this line of code that I can't make any sense of:

nMapperID = ((header.mapper2 >> 4) << 4) | (header.mapper1 >> 4);

Why is header.mapper2 bit-shifted once to the right and then to the left.

The header by the way is this struct:

struct sHeader
{
    char name[4];
    uint8_t prg_rom_chunks;
    uint8_t chr_rom_chunks;
    uint8_t mapper1;
    uint8_t mapper2;
    uint8_t prg_ram_size;
    uint8_t tv_system1;
    uint8_t tv_system2;
    char unused[5];
} header;

Solution

  • A bit-shift is not a rotation of bits. The new bits that appear are all 0s. So this expression:

    (header.mapper2 >> 4) << 4)
    

    first clears the 4 lower order bits, and then shifts all the bits back to the left.

    e.g. if you had a bit pattern like 01010101, the right-shift would first make the bits 00000101, and then the left-shift would make it 01010000 (hence clearing the rightmost 4 bits).

    If it were a rotation of bits (as you seem to expect), then it would indeed be effectively a no-op.