Take the 2-minute tour ×

Given offset OFF and length LEN, isolate a group of bits and shift it to the right. (Usage: int holding several smaller-range integers with given offsets and lengths). For example using offset 4 and length 4,

  a = 110101011000
      ----^^^^---- this is the group 
              ^^^^ isolated and right-shifted here

I currently use


giving for the example above

a                         110101011000
a>>OFF                    000011010101
1<<(LEN+1)                000000010000
1<<(LEN+1)-1              000000001111
(a>>OFF)&((1<<(LEN+1))-1) 000000000101

Is there a more readable/efficient way?

share|improve this question
The expression is fine - just put it in a macro or inline function and forget about it. –  Paul R Jan 16 '12 at 6:57

2 Answers 2

up vote 0 down vote accepted

There isn't a single correct answer in this case. What you did is fine - it's correct, and with some documentation it's also pretty clear.

If you want different ways, you can: try shifting a left and then right again (assuming a is unsigned - otherwise cast it first); or you can first create a mask (in your case: 000011110000), bitwise-and, and only then shift. However, these won't necessarily be prettier than what you already have.

share|improve this answer


Shift left 010110000000

Shift right 000000000101

This is more readable..!

share|improve this answer

Your Answer


