beginnerHacker
beginnerHacker

Reputation: 51

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!

Upvotes: 0

Views: 555

Answers (2)

Adrian McCarthy
Adrian McCarthy

Reputation: 47952

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.

Upvotes: 2

Prune
Prune

Reputation: 77837

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.

Upvotes: 1

Related Questions