Search code examples
c++endiannessbinary-operators

Why is there an unnecessary or operation when inverting bytes?


I am really confused by this, however trivial it may be. Here's an example (which I tried on paper):

uint16_t val               = 32;                      //00000000 00100000
uint16_t swapped           = val >> 8;                //00100000 00000000
uint16_t swapped2          = val << 8;                //00100000 00000000
uint16_t swapped3          = (val >> 8) | (val << 8); //00100000 00000000

I may be missing something... But as far as I know, they all have the same value, I was wondering maybe the operation in "swapped3" was a safeguard/good practice when doing the same for unsigned 32 bit values, but it wouldn't make sense.

I've tried to search answers online, but all operations are either this or a play on it.

Enlighten me, if possible, binary operations make my head spin.


Solution

  • As many has already stated in the comments, the >> and << operations are bitwise shifts, not bitwise rotations. See https://en.cppreference.com/w/cpp/language/operator_arithmetic.

    In the most recent standard (C++20) they've added the rotations as well: see rotr and rotl.