Help with making this prettier?

P

Pito Salas

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
 
C

Chris Howe

[Note: parts of this message were removed to make it a legal post.]

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.
 
P

Pito Salas

Chris said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,899
Latest member
RodneyMcAu

Latest Threads

Top