简体   繁体   中英

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

I'm talking about this:

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

I thought about two ways:

Given x is a byte.

  1. x << 4; x >> 4

  2. x %= 16

Any other ways? Which one is faster?

Brevity is nice - explanations are better :)

  • x &= 0x0f

is, of course, the right answer. It exactly expresses the intent of what you're trying to achieve, and on any sane architecture will always compile down to the minimum number of instructions (ie 1). Do use hex rather than decimal whenever you put constants in a bit-wise operator.

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

will only work if your 'byte' is a proper unsigned type. If it was actually a signed char then the second operation might cause sign extension (ie your original bit 3 would then appear in bits 4-7 too).

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

  • x %= 16

even without the optimizer enabled your compiler will almost certainly do the right thing here and turn that expensive div/mod operation into the first answer. However it can only do that for powers of two, and this paradigm doesn't make it quite so obvious what you're trying to achieve.

我总是使用x &= 0x0f

There are many good answers and some of them are technically the right ones.

In a broader scale, one should understand that C/C++ is not an assembler. Programmer's job is to try to tell to the compiler the intention what you want to achieve. The compiler will pick the best way to do it depending on the architecture and various optimization flags.

x &= 0x0F; is the most clear way to tell the compiler what you want to achieve. If shifting up and down is faster on some architecture, it is the compiler's job to know it and do the right thing.

单个AND运算就可以做到。

x = (x & 0x0F);

It will depend on on the architecture to some extent - shifting up and back down on an ARM is probably the fastest way - however the compiler should do that for you. In fact, all of the suggested methods will probably be optimized to the same code by the compiler.

x = x&15

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM