I can think of three ways to do this off the top of my head. I'll outline them real quick.
char mask = (1<<top)
mask = mask-1
mask = mask>>bot
mask = mask<<bot
3 shifts, 1 addition
char topMask = (1<<top)
topMask = topMask -1
char botMask = (1<<bot)
botMask = botMask - 1
char mask = topMask - botMask
2 shifts, 3 additions
char mask = (1<<(top-bot))
mask = mask - 1
mask = mask << bot
2 shifts, 2 additions
It seems like the first one would be a little faster? Is one considered best for style reasons? Is there a really good way I'm missing, or am I doing something stupid? Thanks!
I'd especially be interested if anyone could point me to a place this is done in the linux kernel.
EDIT: someone posted something like this as another way and deleted it? Pretty similar to the second one. But XOR instead of subtract.
char mask = ((1<<top)-1)^((1<<bot)-1)