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

后端 未结 6 1100
说谎
说谎 2021-02-09 07:00

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:

6条回答
  •  心在旅途
    2021-02-09 07:35

    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 (i.e. 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 (i.e. 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.

提交回复
热议问题