unsigned value( unsigned n, unsigned low, unsigned high ){
if( !(low <= high && high <= 32) ) exit(EXIT_FAILURE);
if( low == 0 && high == 32 )
return n;
else
return n >> low & (1U << (high-low)) - 1;
}
imagine we had the following as n=11100011, low=2, and high=7.
by the time we reached the return statement I’d have this
00111000 & (00100000 – 00000001)
this would be
00111000 & 00011111
which would equal
00011000
but thats not right is it? Thats 24 while I want 00111000 which is 56
what am I doing wrong here? where did I screw up?
You need to left-shift one more position before you subtract 1. That will extend the string of
1bits one more position to the left, which is where thehighbit resides.Imagine the extreme case, where
low = 0andhigh = 32. Ignore the overflow, which is an artifact of the size oflong, and do the calculation:The term on the left is just
n, and the term on the right is a string of 321bits.