Rio
Rio

Reputation: 14882

Algorithmic efficiency in selecting based on bits

I was wondering what your ideas were in developing an efficient algorithm for doing if/else switch/cases based on bits. I have 8 bits to play with and I need to divide them into higher order and lower order bits, like so:

0000 1111

Each half contains some information base on which bits are turned on. For example, if the lower half (1111 in this little endian machine) is actually 0010, something happens. Furthermore, if the higher end is 1000, something else happens.

I guess it would be efficient to rightshift the upper half and make AND comparisons (like (x >> 4) & 8) but I'm not sure what's smart to do for the lower half, as it seems a bit unclever to left shift and compare to some weird number.

Your insights, again, greatly appreciated.

Upvotes: 1

Views: 103

Answers (3)

NPE
NPE

Reputation: 500357

First of all, the (x >> 4) & 8 in your example isn't quite right. To compare the higher nibble (the top four bits) to n, you need ((x >> 4) & 15) == n.

To compare the lower nibble to n, you simply lose the right shift: (x & 15) == n.

Upvotes: 3

Pete Wilson
Pete Wilson

Reputation: 8694

I can't tell whether you want something efficient, as you say, or something clever. If you really want fast execution, nothing is faster than a switch statement with 256 cases. Take a look at the code the compiler produces for switch and you'll see that it's very fast.

If you want something clever, that's a different deal. But, no matter how clever it is, it's never going to be faster than a switch.

Upvotes: 0

x4u
x4u

Reputation: 14077

To mask the lower 4 bits you can use bits & 0xf and if you want to check whether the 4 bits have a certain value (i.e. 2 which is 0010) you can use ( bits & 0xf ) == 2 for the lower half and ( bits >> 4 ) == 2 for the upper half.

Endianess makes no difference when you are looking at just a single byte.

Upvotes: 1

Related Questions