What is the fastest way to get the 4 least significant bits in a byte (C ++)?

I say this:

If we have the letter "A", which is 77 in the decimal system and 4D in Hex. I am looking for the fastest way to get D.

I thought of two ways:

Given that x is a byte.

  • x <4; x → 4

  • x% = 16

Any other ways? Which one is faster?

Thanks.

+7
c ++ optimization operators modulo shift
source share
6 answers

I always use x &= 0x0f

+22
source share

Good delinquency - better explanation :)

  • x &= 0x0f

of course the correct answer. It accurately expresses the intention of what you are trying to achieve, and on any reasonable architecture it will always come down to a minimum number of instructions (i.e. 1). Use hexadecimal rather than decimal every time you put constants in a bitwise operator.

  • x <<= 4; x >>= 4

will only work if your "byte" is the correct unsigned type. If it was actually a signed char, then the second operation can cause the character to expand (i.e., your original bit 3 will also appear in bits 4-7).

Without optimization, this, of course, will take 2 instructions, but with GCC on OSX even -O1 will reduce this to the first answer.

  • x %= 16

Even without an optimizer, your compiler will almost certainly do everything right and turn this expensive div / mod operation into the first answer. However, he can only do this for the forces of two, and this paradigm does not make it so obvious that you are trying to achieve.

+37
source share

There are many good answers, and some of them are technically correct.

On a larger scale, it should be understood that C / C ++ is not an assembler. The programmer's task is to try to tell the compiler about the intent that you want to achieve. The compiler will choose the best way to do this, depending on the architecture and various optimization flags.

x & = 0x0F; is the clearest way to tell the compiler what you want to achieve. If moving up and down is faster in some architecture, the job of the compiler is to know and do the right thing.

+10
source share

Single AND operation can do this.

 x = (x & 0x0F); 
+4
source share

To some extent, this will depend on the architecture - shifting up and back on the ARM is probably the fastest way, but the compiler should do it for you. In fact, all the proposed methods are likely to be optimized for the same code by the compiler.

+2
source share

x = x and 15

0
source share

All Articles