Converting binary string to integer for a Ruby newbie

I want to convert a string of binary code (“011001”) to the integer
value WITHOUT using to_i or any other preset method. How can I do this?

Thanks for reading.

Hi,

if you don’t want to use the built-in methods, you’ll have to loop over
the characters and sum the values of the digits.

The easiest way is to start from right and let an index count from 0 up.
This will give you the exponent of each power of 2:

num = ‘011001’
value = 0
‘011001’.reverse.each_char.with_index do |dig, i|
value += 2**i if dig == ‘1’
end
puts value

So for every digit “1”, you add the corresponding value.

On 10/16/2012 8:16 PM, John R. wrote:

I want to convert a string of binary code (“011001”) to the integer
value WITHOUT using to_i or any other preset method. How can I do this?

Thanks for reading.
curios:Why?

“011001”.each_char.reverse_each.with_index.inject(0) {|v,(dig,i)| v +
(dig == ‘1’ ? 2**i : 0 )} #=> 25

or use rubys cool features: Integer(“0b” + “011001”) #=> 25

2012/10/16 Hans M. [email protected]:

“011001”.each_char.reverse_each.with_index.inject(0) {|v,(dig,i)| v +
(dig == ‘1’ ? 2**i : 0 )} #=> 25

Well that’s totally helpful for someone trying to learn a new
language, or possibly programming. And totally readable for seasoned
devs. /sarcasm

+1 for Jan’s answer.

– Matma R.

John R. wrote in post #1080074:

I want to convert a string of binary code (“011001”) to the integer
value WITHOUT using to_i or any other preset method. How can I do this?

Thanks for reading.

One of many solutions:

res = 0
str.each_char do |c|
res *= 2
res +=1 if c == “1”
end

On Wed, Oct 17, 2012 at 3:16 AM, John R. [email protected]
wrote:

I want to convert a string of binary code (“011001”) to the integer
value WITHOUT using to_i or any other preset method. How can I do this?

You can try this.

n = “0011001”

t = 0
n.each_char{|x| t = t*2+x.to_i}
p t

But if you are against using #to_i even like this, you could try this…

t = 0
n.each_char{|x| t = x==“1” ? t2+1 : t2}
p t

Or maybe,

t=0
n.each_char{|x| t=t*2+(x<=>“0”)}
p t

Harry

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs