# Help with making this prettier?

**URL:** <https://www.ruby-forum.com/t/help-with-making-this-prettier/172171>\
**Category:** Ruby\
**Created:** [July 16, 2009, 4:26am UTC](https://www.ruby-forum.com/t/help-with-making-this-prettier/172171 "2009-07-16T04:26:39Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![pitosalas](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/a4c791/32.png) [@pitosalas](https://www.ruby-forum.com/u/pitosalas)\
**Post date:** [July 16, 2009, 4:26am UTC](https://www.ruby-forum.com/t/help-with-making-this-prettier/172171/1 "2009-07-16T04:26:39Z")

</div>

What I want to do is to extract the integer value corresponding to a bit  
field within a FixNum. That is, for example, what is the integer value  
formed by bits 4,5,6,7,8 of a number?

This is my ugly first cut. There must be a library function that does  
this but I can’t find it. Anyone have a pointer, that would be great!!  
Or a suggestion on refactoring/rewriting this?

Thanks!

def bit\_field(from, to, val)  
accum = 0  
ind = 0  
from.upto(to) do |index|  
bitval = val[index]  
accum = accum + bitval \* (2 \*\* ind)  
ind = ind + 1  
end  
accum  
end

---

<div class="post-metadata">

**Author:** ![pitosalas](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/a4c791/32.png) [@pitosalas](https://www.ruby-forum.com/u/pitosalas)\
**Post date:** [July 16, 2009, 9:51am UTC](https://www.ruby-forum.com/t/help-with-making-this-prettier/172171/2 "2009-07-16T09:51:25Z")

</div>

How about this:

def bit\_field(from,to,val)  
return ( val\>\>from ) & ( (2 \<\< (to - from) ) - 1)  
end  
In binary 2\<\<(to-from) is going to be a 1 with (to-from+1) zeros after  
it,  
subtracting 1 leaves you with just (to-from+1) 1’s in the lower bits of  
the  
number.

val\>\>from shifts the bit field over to the lower bits.

Bitwise anding the two together masks off the upper order bits of val,  
leaving you with the value you are looking for.

---

<div class="post-metadata">

**Author:** ![pitosalas](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/a4c791/32.png) [@pitosalas](https://www.ruby-forum.com/u/pitosalas)\
**Post date:** [July 16, 2009, 9:20pm UTC](https://www.ruby-forum.com/t/help-with-making-this-prettier/172171/3 "2009-07-16T21:20:01Z")

</div>

Chris Howe wrote:

> How about this:
> 
> def bit\_field(from,to,val)  
> return ( val\>\>from ) & ( (2 \<\< (to - from) ) - 1)  
> end  
> In binary 2\<\<(to-from) is going to be a 1 with (to-from+1) zeros after  
> it,  
> subtracting 1 leaves you with just (to-from+1) 1’s in the lower bits of  
> the  
> number.
> 
> val\>\>from shifts the bit field over to the lower bits.
> 
> Bitwise anding the two together masks off the upper order bits of val,  
> leaving you with the value you are looking for.

Thanks. Beautiful, and nice explanation too!

- Pito
