Convert binary array to floating point decimal

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 binaryStringToFloat(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

On 12/3/06, Nebiru [email protected] 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)
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

Wow, so much learned in one post…thank you

On 12/3/06, Martin DeMello [email protected] wrote:

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

that should be

str.to_i(2) * 1.0/(1 << str.length)

of course

martin