beginnerHacker February 2016

Obtaining bits from a byte without shifts

I am trying to obtain a number of bits from a byte in C. Currently I am doing so by shifting and then bit masking (0xFF), however the shifting operator is taking a long time. Is there another way to this using only bitwise operations? And if so how?

Thanks!

Answers


Prune February 2016

I'm afraid not. Each of the bit positions is an independent data stream. So long as you're restricted to these, no amount of bit-wise operation will make one bit affect any position other than its own.

Even if you allow basic arithmetic, the appropriate operations -- multiply and divide by powers of 2 -- are slower and less obvious than the shift operations.


To shift right N bits, divide by 2^N. To shift left N bits, multiply by 2^N.

If the bits are in the same place every time, and you can use them where they are, then move your mask. For instance

word & 0x3FC0

will get you bits 2-9 (or 13-6, depending on your indexing) of the word.

As before, though, I would be surprised to find that arithmetic is faster than shifting. What platform are you using where shift is slow? Most processors have this as a machine instruction.


Since you're not sharing details of the machine or application, about all I can suggest is to shift to the nearest byte boundary -- no more than 4 bits away -- and extract the desired value by accessing the byte. If that still isn't a reasonable solution for you, then I'll wait for a proper problem description.


Adrian McCarthy February 2016

If you want to move a particular (single) bit to the least-significant position, you can use a hack like this:

(x & mask) != 0

where mask selects the single bit.

Post Status

Asked in February 2016
Viewed 2,717 times
Voted 14
Answered 2 times

Search




Leave an answer