0

How can I optimize int a = b % 16 using bitwise operations? Tried with >> 4 but I am missing something.

  • 9
    `int a = b & 0xf;` – Iłya Bursov Jun 16 '22 at 19:14
  • 7
    highly likely that the compiler will optimize this for you anyway (if you compile with optimizations turned on), there is absolutely no need for you to do it manually – Jane Doe Jun 16 '22 at 19:17
  • When you look at a number like `1234` and you want to know that number **mod 100** you can simply read off the last two digits to get `34`. Similarly, in binary, if you want to know the number mod some-power-of-two, you can read off (mask off) the last n bits. assuming you're doing mod (2^n). (as Iłya Bursov has shown) – Wyck Jun 16 '22 at 19:18
  • What make you think bitwise operations are more efficient than modulo division? They might be in assembly but in C++ if a modulo division can efficiently be turned into bitwise operations then the compiler will do it for you (at least if you enable optimisations). Compilers are smart. – john Jun 16 '22 at 19:19
  • 1
    Compile with `-O2` or `-O3` – NathanOliver Jun 16 '22 at 19:23
  • Does this answer your question? [Bitwise and in place of modulus operator](https://stackoverflow.com/questions/3072665/bitwise-and-in-place-of-modulus-operator) – Mohamad Ziad Alkabakibi Jun 16 '22 at 19:25
  • Handy reading: [The as-if rule](https://en.cppreference.com/w/cpp/language/as_if). TL;DR version: don't think of code as a list of instructions you want the computer to perform, think of it as a description of behaviour that the compiler will transform into the most efficient list of instructions that it can. – user4581301 Jun 16 '22 at 19:28
  • `b >> 4` is not equivalent to `b % 16`. It is equivalent to `b / 16`. (Assuming unsigned) – Wyck Jun 16 '22 at 19:28
  • 3
    Beware that n & 0xf and n % 16 will give different results for negative n. –  Jun 16 '22 at 19:29
  • Trust the optimizer. Compiler optimizers are truly incredibly amazing. Write the code for legibility. If `% 16` is the correct thing to convey to a reader of the code, then use `% 16`. If `& 0xF` is the correct thing to convey, in the context, then use that. **Profile**, to find if there are bottlenecks that need to be hand-optimized. Never hand-optimize without profiling, because otherwise you won't know if the inscrutable code is any better than the straightforward code (and may actually be worse). – Eljay Jun 16 '22 at 19:29
  • And use unsigned types where possible as they can be optimized better. – Goswin von Brederlow Jun 16 '22 at 20:34

0 Answers0