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;
}

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 +
}