Nebiru
12/2/2006 8:43:00 PM
Wow, so much learned in one post...thank you
Martin DeMello wrote:
> On 12/3/06, Nebiru <Nebiru@gmail.com> wrote:
> > new to ruby here, looking for a little help
> >
> > I'm trying to convert some C# code to ruby, however I'm not getting the
> > desired results
> > The code is supposed to convert a binary string to a floating point
> > number
> >
> > public float
> (int length)
> > {
> > float result = 0;
> > int num = 0;
> > // form the integer number from the binary string
> > for (int i = 0; i < length; i++)
> > {
> > num = num << 1;
> > num = num + binaryArray[(length - i) - 1];
> > }
> > // scale to the floating point value
> > result = (float)num;
> > result = result / (1 << binaryArray.length/2);
> > return result;
> > }
> >
> > any help will be appreciated
>
> Ruby has a built in method for converting a binary string into an
> integer, so your code is simply
>
> def binaryStringToFloat(str)
> str.to_i(2) * 1.0/str.length
> end
>
> but if you want to translate your algorithm literally:
>
> def binaryStringToFloat(str)
> num = 0
> # reverse the string, split it into characters, then iterate over
> the characters
> str.reverse.split(//).each {|digit|
> num = (num << 1) + digit.to_i # << has lower precedence than +
> }
>
> return num * 1.0 / (1 << str.length)
> end
>
> also, the pattern
>
> accumulator = start_val
> collection.each {|element|
> accumulator = f(accumulator, element)
> }
>
> is captured by the inject method, so we can replace the "each" loop with
>
> num = str.reverse.split(//).inject(0) {|sum, digit| (sum << 1) + digit .to_i}
>
> martin